Contents
  1. 1. Expression
    1. 1.1. Invocation Expressions
      1. 1.1.1. Conditional Invocation
    2. 1.2. Null Check
  2. 2. Statement
    1. 2.1. For Loop
    2. 2.2. Print to console
  3. 3. Object
    1. 3.1. Traversing JavaScript Object
  4. 4. Array
    1. 4.1. Traversal
    2. 4.2. Find Max in an array
    3. 4.3. Convert type of elements of Array
  5. 5. Request
    1. 5.1. URL Parameters
  6. 6. Document
    1. 6.1. Remove Elements
    2. 6.2. Empty Elements
  7. 7. Regular Expression
  8. 8. References

Content

  • Types, Values, and Variables
  • Expression, Statement, Functions
  • Objects, Classes
  • Arrays
  • Sync
  • JavaScript in Web Browsers
  • Modules

Expression

Invocation Expressions

Conditional Invocation

1
let result = json?.name;
1
let result = json != null ? json.name : undefined;

Null Check

if a != null return a, else return default value

1
2
// Ternary Operator
let result = a != null ? a : defaultValue;
1
2
3
// Logical Operator ||
// When it's used with non-boolean values, the || operator will return a non-boolean value of one of the specified expression or operands.
let result = a || defaultValue;
1
2
// Nullish Coalescing Operator ??
let result = a ?? defaultValue;

2

if a != null and b != null return b; else return null;

1
let result = a != null && a.name != null ? a.name : null;
1
let result = a && a.name;

Statement

For Loop

1
2
3
4
for (let i = 0; i < arr.length; ++i)
arr.forEach((value, index) => { /* ... */ })
for (let index in arr)
for (const value of arr)

console.log(obj1 [, obj2, ..., objN]);

1
2
3
4
5
6
console.log(obj)
console.log(obj1, obj2)
console.log("obj is: ", obj)
console.log("obj is: ", obj, ". And my name is ", name)
console.log("objects are: ", obj1, obj2)
console.log("obj is: " + JSON.parse(JSON.stringify(obj)))

console.log(msg [, subst1, ..., substN]);

  • %o or %O Outputs a JavaScript object.
  • %d or %i Outputs an integer.
  • %s Outputs a string.
  • %f Outputs a floating-point value.
1
2
console.log("obj is %o", obj)
console.log("Hello, %s. You've called me %d times.", "Bob", 1);

Object

Merge object fields

1
2
3
4
5
let json1 = {"name": "Jack"};
let json2 = {
...json1,
age: 18
};

Deep copy

1
2
let json = {"name": "Jack"};
let copy = JSON.parse(JSON.stringify(json));

Get all keys of JSON/JavaScript object

1
2
const obj = {a: 'somestring', b: 123, c: false};
Object.keys(obj);

Get all values of JSON/JavaScript object

1
2
const obj = {a: 'somestring', b: 123, c: false};
Object.values(obj);
1
2
3
// ES6
const obj = {a: 'somestring', b: 123, c: false};
Object.keys(obj).map(key => obj[key]);

Traversing JavaScript Object

for-in

1
2
3
4
5
// iterates over all enumerable properties of an object.
const jsonObj = {name: "Jack", age: 18}
for (const key in jsonObj) {
console.log(`${key}: ${jsonObj[key]}`);
}

Object.entries() or Object.keys()

1
2
3
4
5
// to traverse a Javascript object
const jsonObj = {name: "Jack", age: 18}
Object.entries(jsonObj).forEach(([key, value]) => {
console.log(key, value)
});
1
2
3
4
Object.keys(obj).forEach(function(key) {
var value = obj[key];
// ...
});

to include non-enumerable properties

1
2
3
4
Object.getOwnPropertyNames(obj).forEach(function(key) {
var value = obj[key];
// ...
});

Array

Traversal

1
2
3
4
for (let i = 0; i < arr.length; ++i)
arr.forEach((value, index) => { /* ... */ })
for (let index in arr)
for (const value of arr)

forEach: executes a provided function once for each array element. another type of for loop.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

1
2
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

for in: iterates over all enumerable properties of an object. E.g. key of JSON object, index of array.

1
2
3
4
5
const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
console.log(`${property}: ${object[property]}`);
}

for of: The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

1
2
3
4
5
const array1 = ['a', 'b', 'c'];

for (const element of array1) {
console.log(element);
}
1
2
3
for (const [idx, el] of arr.entries()) {
console.log( idx + ': ' + el );
}

Summary

If you don’t need break for loop use forEach, else use for of.

Find Max in an array

Find max value in an array

1
2
3
4
5
6
// apply
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
Math.max.apply(Math, array.map(o => o.value));

const array = [1,2,3,5,1,2]
Math.max.apply(Math, array);
1
2
3
4
5
6
// ES6 spread
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
Math.max(...array.map(o => o.value));

const array = [1,2,3,5,1,2]
Math.max(...array);
1
2
3
4
5
6
7
// standard loop
let max = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
if (testArray[i] > max) {
max = testArray[i];
}
}
1
2
3
4
5
6
// reduce
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
array.reduce((a, b) => Math.max(a.value, b.value));

const array = [1,2,3,5,1,2]
array.reduce((a, b) => Math.max(a, b));

Time cost: standard loop < ES6 spread and apply < reduce

Finding the max value of an attribute in an array of objects

1
2
3
// reduce
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
const maxValueObject = array.reduce((prev, current) => (prev.value > current.value) ? prev : current)

Convert type of elements of Array

int array to string array

1
2
3
// This will not mutate array. It will return a new array.
let array = [1, 2, 3];
let newArray = array.map(String);
1
2
let array = [1, 2, 3];
let newArray = array.map(item => item.toString())
1
2
let array = [1, 2, 3];
let newArray = array.join(",").split(",");

string array to int array

1
2
3
// Note: For older browsers that don't support map
let array = ['1', '2', '3'];
let newArray = array.map(Number); // i=>Number(i)
1
2
let array = ['1', '2', '3'];
let newArray = array.map(item => parseInt(item));
1
2
let array = ['1', '2', '3'];
let newArray = Array.from(array, Number);

Request

URL Parameters

Getting URL parameters

1
2
3
4
5
6
// https://example.com/?id=1
const queryString = window.location.search;
console.log(queryString); // ?id=1
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');
console.log(id); // 1

Checking for the Presence of a Parameter

1
console.log(urlParams.has('id')); // true

Getting All of a Parameter’s Values

1
2
3
4
5
6
7
8
console.log(urlParams.getAll('size'));
// [ 'm' ]

//Programmatically add a second size parameter.
urlParams.append('size', 'xl');

console.log(urlParams.getAll('size'));
// [ 'm', 'xl' ]

Iterating over Parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const
keys = urlParams.keys(),
values = urlParams.values(),
entries = urlParams.entries();

for (const key of keys) console.log(key);
// product, color, newuser, size

for (const value of values) console.log(value);
// shirt, blue, , m

for(const entry of entries) {
console.log(`${entry[0]}: ${entry[1]}`);
}

Document

Remove Elements

remove element by id

1
document.querySelector("#remove").remove();

remove elements by class name

1
2
3
4
5
6
function removeElementsByClass(className){
const elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
1
const removeElementsByClass = (className) => document.querySelectorAll(className).forEach(el => el.remove());

Empty Elements

empty element by id

1
document.querySelector("#remove").innerHTML = "";

empty elements by class name

1
const emptyElementsByClass = (className) => document.querySelectorAll(className).forEach(el => el.innerHTML = "");

Regular Expression

RegExp

1
2
3
// creating regular expression from a string, you have to double-up your backslashes \\.
const regex = new RegExp('^\\d{10}$');
const regex = new RegExp('^\\d{10}$', 'g');

/regex/mod

1
2
3
// if you use regex syntax, you need eacape / by \/
const regex = /^\d{10}$/;
const regex = /^\d{10}$/g;

API

  • RegExp

    • regexp.exec(str) - Returns the first match info array. It likes [matched string, group 1, group 2, ...]. The flag g has no effect.

      1
      2
      /hello(\d)/.exec("hello1, hello2"); // ['hello1', '1', ...]
      /hello(\d)/g.exec("hello1, hello2"); // ['hello1', '1', ...]
    • regexp.test(str) - Returns whether it matches. The flag g has no effect.

      1
      2
      /hello(\d)/.test("hello1, hello2"); // true
      /hello(\d)/g.test("hello1, hello2"); // true
  • String

    • string.match(regexp) - Returns the first match info array [matched string, group 1, group 2, ...], or return an all matched string array [matched string 1, matched string 2, ...] when it uses the flag g.

      1
      2
      3
      let s = "hello1, hello2";
      s.match(/hello(\d)/); // return the first match object ['hello1', '1', ...]
      s.match(/hello(\d)/g); // return all match strings ['hello1', 'hello2']
    • string.matchAll(regexp) - Returns all match info arrays. The regexp must use the flag g (global search).

      1
      2
      3
      4
      5
      6
      7
      let s = "hello1, hello2";
      s.matchAll(/hello(\d)/); // Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument
      for (const match of s.matchAll(/hello(\d)/g)) {
      console.log(match); // the match info array
      console.log(match[0]); // the matched string
      console.log(match[1]); // the group 1 of the matched string
      }
    • string.replace(regexp, replacement) - Returns a string with the first or all matched string replaced.

      1
      2
      3
      let s = "hello1, hello2";
      s.replace(/hello(\d)/, 'hey'); // 'hey, hello2'
      s.replace(/hello(\d)/g, 'hey'); // 'hey, hey'
      1
      2
      3
      4
      5
      6
      // replace with group
      let s = "hello1, hello2";
      s.replace(/hello(\d)/, "hi$1"); // 'hi1, hello2'
      s.replace(/hello(\d)/g, "hi$1"); // 'hi1, hi2'
      // extract group
      s.replace(/hello(\d)/g, "$1"); // '1, 2'
    • string.replaceAll(regexp, replacement) - Returns a string with the all matched string replaced. The regexp must use the flag g (global search).

      1
      2
      3
      let s = "hello1, hello2";
      s.replaceAll(/hello(\d)/, 'hey'); // Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
      s.replaceAll(/hello(\d)/g, 'hey'); // 'hey, hey'
      1
      2
      3
      4
      // replace with group.
      // replaceAll(/xxx/g, '') results are same with replace(/xxx/g, '')
      s.replaceAll(/hello(\d)/g, "hi$1"); // 'hi1, hi2'
      s.replaceAll(/hello(\d)/g, "$1"); // '1, 2'
    • string.search(regexp)

    • string.split(regexp)

Flags

Flag Description Corresponding property
d Generate indices for substring matches. hasIndices
g Global search. global
i Case-insensitive search. ignoreCase
m Allows ^ and $ to match newline characters. multiline
s Allows . to match newline characters. dotAll
u “Unicode”; treat a pattern as a sequence of Unicode code points. unicode
v An upgrade to the u mode with more Unicode features. unicodeSets
y Perform a “sticky” search that matches starting at the current position in the target string. sticky

References

Contents
  1. 1. Expression
    1. 1.1. Invocation Expressions
      1. 1.1.1. Conditional Invocation
    2. 1.2. Null Check
  2. 2. Statement
    1. 2.1. For Loop
    2. 2.2. Print to console
  3. 3. Object
    1. 3.1. Traversing JavaScript Object
  4. 4. Array
    1. 4.1. Traversal
    2. 4.2. Find Max in an array
    3. 4.3. Convert type of elements of Array
  5. 5. Request
    1. 5.1. URL Parameters
  6. 6. Document
    1. 6.1. Remove Elements
    2. 6.2. Empty Elements
  7. 7. Regular Expression
  8. 8. References