Categories
JavaScript Basics

JavaScript Cheat Sheet — Operators and Dates

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Operators

We can do arithmetic with JavaScript.

We add with + and subtract with - :

let a = b + c - d;

We multiply with * and divide with / :

let a = b * (c / d);

And we get the remainder of one number divided by another with / :

let x = 100 % 48;

We increment with ++ :

a++;

And we decrement with -- :

b--;

Typeof

We can get type of primitive values and objects with typeof :

typeof a

It’s mostly useful for primitive values since it returns 'object' for all objects.

Assignment

We assign one value to a variable with = :

let x = 10

The right expression is assigned to the variable on the left.

a +=b is short for a = a + b . We can also replace + with - , * and / .

Comparison

We compare equality with === :

a === b

We check for inequality with !== :

a !== b

We check if a is greater than b with:

a > b

And we check if a is less than b with:

a < b

We can check for less than or equal with:

a <= b

And we check for greater than or equal with:

a >= b

Logical AND is && :

a && b

And logical OR is || :

a || b

Dates

We can create date objects with the Date constructor:

let d = new Date("2017-06-23");

If we omit the month and day, then it’s set to January 1:

let d = new Date("2017");

We can add the hour, minutes, and seconds with:

let d = new Date("2017-06-23T12:00:00-09:45");

Human readable date also works:

let d1 = new Date("June 23 2017");
let d2 = new Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)");

A date object comes with methods to let us get various values from it.

We call them by writing:

let d = new Date();
let a = d.getDay();

getDay() gets the day of the week

getDate() gets the day of the month as a number.

getFullYear() gets the 4 digit year.

getHours() gets the hours.

getMilliseconds() gets the milliseconds.

getMinutes() gets the minutes.

getMonth() gets the month.

getSeconds() gets the seconds.

getTime() gets the milliseconds since 1970, January 1.

We can also set values with some setter methods.

To call them, we write:

let d = new Date();
d.setDate(d.getDate() + 7);

setDay() sets the day of the week

setDate() sets the day of the month as a number.

setFullYear() sets the 4 digit year.

setHours() sets the hours.

setMilliseconds() sets the milliseconds.

setMinutes() sets the minutes.

setMonth() sets the month.

setSeconds() sets the seconds.

setTime() sets the timestamp.

Conclusion

JavaScript comes with various operators and the Date constructor to let us create, get, and set dates.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Spread, Variables, and Conditionals

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Spread Operator

We can use the spread operator to add properties from other objects to an object.

For instance, we can write:

const a = {
 frstName: "james",
 lastName: "smith",
}
const b = {
 ...a,
 lastName: "White",
 canSing: true,
}

Then b is:

{
  "frstName": "james",
  "lastName": "White",
  "canSing": true
}

Destructuring Nested Objects

We can destructure nested objects into variables.

For instance, we write:

const bob = {
  name: "bob jones",
  age: 29,
  address: {
    country: "Westeros",
    state: "Crownlands",
    pinCode: "500014",
  },
};
const {
  address: {
    state,
    pinCode
  },
  name
} = bob;

Then state is 'Crownlands' and pinCode is '500014' .

Exponent Operator

We can use the exponent operator to do exponentiation.

So we can write: 2 ** 8 and get 256.

Promises with finally

We can call finally to run code regardless of the result of a promise.

For example, we write:

Promise.resolve(1)
  .then((result) => {})
  .catch((error) => {})
  .finally(() => {})

if-else

We can use a if-else to write code that runs conditionally.

For instance, we can write:

if ((age >= 15) && (age < 19)) {
  status = "Eligible.";
} else {
  status = "Not eligible.";
}

If age is between 15 and 19 then the first block runs.

Otherwise, the 2nd block runs.

Switch Statement

We can use the switch statement to check for more than one case and run code if the value matches.

For instance, we write:

switch (new Date().getDay()) {
  case 6:
    text = "Saturday";
    break;
  case 0:
    text = "Sunday";
    break;
  default:
    text = "";
}

If getDay returns 6 then text is 'Saturday' .

If it returns 0, then text is 'Sunday' .

Otherwise, text is an empty string.

Assign Variables

We can assign variables with let :

let x

x is uninitialized.

We can initialize it:

let y = 1

We can assign it a string:

let a = 'hi'

We can assign it an array:

let b = [1,2,3]

And we can assign it a boolean:

let c = false;

And regex:

let d = /()/

Or assign it a function:

let e = function(){};

And we can create a constant:

const PI = 3.14;

We can assign multiple variables in a line:

let a = 1, b = 2, c = a + b;

Strict Mode

We can add 'use strict' to our code to make us write better JavaScript code.

For instance, we can’t write code like:

a = 1

since strict mode will stop global variables from being created.

Values

JavaScript has some values like booleans:

false, true

Numbers:

1.2, 0n001, 0xF6, NaN

Strings:

'foo', 'bar'

And reserved words for special values:

null, undefined, Infinity

Conclusion

JavaScript comes with various constructs to help us create programs.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Basic ES6 Syntax and Methods

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Arrow function

const sum = (a, b) => a + b

sum(1, 2) returns 3.

Default parameters

function print(a = 5) {
  console.log(a)
}

print() logs 5.

let scope

We can use let to declare variables:

let a = 3
if (true) {
  let a = 10
  console.log(a)
}

console.log should log 10.

const

const variables can only be assigned once when we initialize it:

const a = 11

We’ll get an error if we try to assign a again.

Multiline String

We can create multine string with backticks (`):

console.log(`
  This is a
  multiline string
`)

Template Strings

We can interpolate expressions with ${} :

const name = 'james'
const message = `Hello ${name}`

Then message is 'Hello james'

String includes()

We can use the includes method to check if a string has the given substring.

So

'apple'.includes('pl')

returns true .

String startsWith()

The startsWith method lets us check if a string starts with a given substring:

'apple'.startsWith('ap')

String repeat()

We can use the repeat method to repeat a string:

'ab'.repeat(3)

returns ‘ababab’ .

Destructuring Array

We can use the destructuring syntax to assign array entries to variables.

For instance, we write:

let [a, b] = [3, 10];

Then a is 3 and b is 10.

Destructuring Object

We can assign object properties to variables with the destructuring syntax.

For example, if we have:

let obj = {
  a: 15,
  b: 20
};
let {
  a,
  b
} = obj;

Then a is 15 and b is 20.

Object Property Assignement

We can assign properties to objects with the object property assignment syntax.

For instance, we write:

const a = 2
const b = 5
const obj = {
  a,
  b
}

Then obj is:

{a: 2, b: 5}

Object Function Assignment

We can add methods to an object with the shorthand syntax:

const obj = {
  a: 'foo',
  b() {
    console.log('b')
  }
}

Then we can call obj.b() to log 'b' .

Spread Operator

The spread operator lets us combine arrays into one.

For instance, we write:

const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]

And c is [1, 2, 3, 4] .

Object.assign()

The Object.assign method lets us combine multiple objects into one.

For instance, we write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const obj3 = Object.assign({}, obj1, obj2)

Then obj3 is { a: 1, b: 2 } .

Object.entries()

We can get the object’s key-value pairs into an array with the Object.entries() method.

For instance, we write:

const obj = {
  frstName: 'james',
  lastName: 'smith',
  age: 22,
  country: 'uk',
};
const entries = Object.entries(obj);

Then Object.entries returns:

[
  [
    "frstName",
    "james"
  ],
  [
    "lastName",
    "smith"
  ],
  [
    "age",
    22
  ],
  [
    "country",
    "uk"
  ]
]

Conclusion

JavaScript comes with useful syntax and methods in the standard library we can use.

Categories
Tools

Useful Linux Commands — Users, Groups, and Remote Connections

Linux is an operating system that many developers will use.

Therefore, it’s a good idea to learn some Linux commands.

In this article, we’ll look at some useful Linux commands we should know.

printf

printf is an improved version of the echo command.

It lets us format and adds escape sequences:

printf "1\n3\n2"

We can also use it with < to get input from it and sort it with sort :

sort <(printf "1\n3\n2")

0 / 1 / 2

0, 1, and 2 are the standard input, output, and error streams, respectively.

For instance, we can redirect to stdout with:

echo "stdout" >&1

And we can redirect to stderr with:

echo "stderr" >&2

users

The users command shows all the users currently logged in.

To see all users on the system, we can check /etc/passwd .

useradd

To add a user to the system, we run useradd .

For instance, we run:

sudo useradd foo

to add the foo user.

userdel

userdel lets us delete the user.

For example, we run:

`sudo` userdel `foo`

to delete the foo user from the system.

groups

groups show all the groups of which the current user is a member.

We can see all groups in the /etc/group .

We shouldn’t change /etc/group unless we know what we’re doing.

groupadd

groupadd lets us add groups into our system.

We can run:

sudo groupadd foo

to add the foo group.

groupdel

groupdel lets us delete a group.

We can run:

sudo groupdel foo

to delete a group.

cmp

cmp gets the byte difference between 2 files.

For instance, we run:

cmp a b

to get the byte difference between files a and b .

cut

cut lets us cut a line into sections on some delimited.

The -d flag lets us specify a delimiter.

-f specifies the field index to print.

For instance, we run:

printf "117.99.234.23" > c
cut -d'.' c -f1

to print 117 onto the screen.

sed

sed lets us replace a string with another string in a file.

For instance, we runL

echo "old" | sed s/old/new/

to remove old with new .

ssh

ssh lets us connect from one machine to another machine.

We run:

ssh –p <port> bob@1.2.3.4

to connect to machine with IP address 1.2.3.4 with user bob .

scp

We can use scp to copy a file securely from one machine to another.

For instance, we can run:

scp –P <port> hello bob@1.2.3.4:~

to copy the hello file from the machine with IP address 1.2.3.4.

rsync

The rsync utility lets us copt files with the least amount of data possible being transmitted.

This is done by looking at changes between files.

For instance, we run:

rsync -av ../s/* .

to sync the files from the ../s directory with the current directory with rsync .

rsync also works over ssh .

We run:

rsync -avz -e "ssh -p <port>" bob@1.2.3.4:~/s/* .

to copy the data over to the machine with IP 1.2.3.4.

Conclusion

We can print files, manipulate users and groups, and connect to other machines with some Linux commands.

Categories
Tools

Useful Linux Commands — Files and Packages

Linux is an operating system that many developers will use.

Therefore, it’s a good idea to learn some Linux commands.

In this article, we’ll look at some useful Linux commands we should know.

head

The head command outputs the first few lines of a file.

The -n flag specifies how many lines to shows.

The default number of lines to show is 10.

tail

tail outputs the last few lines of a file.

We can also use the -n flag to specify how many lines to show.

Also, we can get the end of the file beginning with the N -th line with:

tail -n +N

cat

cat concatenates list of files and send them to the standard output stream.

less

less is a quick tool to let us view a file.

It opens up the file content with a read-only window.

nano

nano is a small text editor.

It’s easy to use for beginners since we don’t have to learn lots of shortcuts.

nedit

nedit is a small graphical rextr editor.

And it lets us edit text with point and click, drag and drop, and syntax highlighting.

touch

touch lets us modify the timestamp of an existing file and quickly create a new file.

logout

logout lets us exit the shell we’re logged into.

ncdu

ncdu lets us display file space usage.

It opens a window that shows the disk usage of each file.

top

top displays all currently running processes and their owners, memory usage, and more.

htop

htop is an interactive version of top .

We can pass -u username to display processes that are owned by user username .

whereis

whereis lets is search for files related to a particular command.

For instance, we run:

whereis ls

to find the path to the ls command and the associated manpage.

whatis

whatis prints the description of the command from its man page.

locate

The locate command finds a file anywhere in the system by searching a cached list of files.

find

find iterates through the file system to find the file we’re looking for.

It looks at files that currently exist in the system.

find lets us search by file age, size, ownership, type, timestamp, permissions, depth within the file system, regex, and more.

wget

wget lets us download a file from the Internet

curl

curl can be used like wget , but we need the --output flag.

curl supports many moe protocols and it’s more widely available that wget .

wget can only receive data, but curl can also send data.

wget can download files recursively, but curl can’t.

apt

The apt command is available in Debian based distros.

It can be used to install, upgrade, or delete software on our machine.

We can run apt search to search for packages. apt install lets us install packages.

Conclusion

Linux distros comes with many commands that we can use to manage files and download files.