Javascript

Basic Syntax

Uses camelCase for variables and function names.

Uses braces for blocks. These also define scopes

if (true) {
}

Uses two spaces for indentation. Prettier will likely handle this automatically.

Comments

Comments are done as follows

// Comment
/* 
Multiline Comment 
*/

Statements should end with a ;. Editors might handle this automatically.

Variables

let name = "Mark"
name = "Mark 2" // Reassign, let not needed

Variables are defined to particular scopes (remember, the braces define scope)

if (condition) {
let name = "Mark"
}
let name = "Mark" // A different scope

However, global variables (to the file level) would be available in different scopes.

let name = "Mark"
function doSomething() {
log name
}

Javascript has the concept of shadowing. You can create variables with the same name, so long as they are in different scopes.

Note that the following will cause an error. It is the shadowing that is causing this error. The interpreter will look through the scope and reserve any names that it needs (which would be name), thus causing the error on line 3 (as it has not been defined yet at that stage).

let name = "Mark"
{
console.log(name)
let name = "John"
console.log(name)
}

Constants

Always create constants unless you intend to change something later.

const name = "Mark"
name = "John" // Will cause an error

Conditionals

Use === for equality, == is messy in most situations, but is useful in some situations.

Warning

You cannot use === to compare arrays. See this post for more details.

A simple function can be created to easily compare arrays using the toString() method.

const compareArrays = (a, b) => {
  return a.toString() === b.toString();
};

Use && to specify the AND operation.

Use || to specify the OR operation.

Loops

A loop in javascript looks like this. See this Stackoverflow post for more information

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Datatypes

Numbers

Numbers are always Floating Point (64-bit). Take care to round numbers where appropriate.

Strings

Strings are immutable, they cannot be changed.

Arrays

1-dimensional collections of data. These are mutable and indexed (starting at 0).

let array = ["Hello", 42]

Elements can be changed via the index

array[1] = 41
log(array) // ["Hello", 41]

If you try to add to an index that is not next in sequence, the list will expand and fill in empty.

array[10] = 44
log(array) // ["Hello", 41, empty x 8, 44]

Table of Contents