JavaScript quick reference

Arrays

Loop through an array

Use a simple for loop:

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

Or use for...of for better readability:

for (const element of array) {
  console.log(element);
}

Speed comparison: (http://jsbench.github.io/#8ed37bb81a337674e317ab5625c701ea)

Do not use:

Determine if a value is in an array

array.includes(value);

Maps

Note: Use Map when you want a key/value associative array and you want to guarantee the insertion order. Otherwise, the convention is to use a simple JavaScript object.

Iterating over a Map

Use for..of:

Logging

Logging non-primitive variables

When you wish to log a non-primitive variable, it’s best to log it directly, e.g.

console.log(myMap);
console.log('myMap=', myMap);

If you use one of these methods, the string conversion will cause some loss of data and will not work for certain objects such as Maps:

console.log(JSON.stringify(myMap));
console.log(`myMap=${myMap}`);
console.log('myMap=' + myMap);

Objects

Iterate over an object

See https://stackoverflow.com/a/684692/399105