Single line Comments: //
Multi-line Comments: /* ... */
// Syntax:
// function <fn_name>(<args_list>) { <body> }
// Example function that adds two values
function add(a, b) {
return a + b;
}
[const | let | var] <fn_name> = (<args_list>) => { <body> };
// Parentheses around body are optional. When ommited, returns the evaluated value by default
// The same "add" function above can be written as:
const add = (a, b) => a + b;
// Arrow functions (or lambda expressions) do not have their own scope (this),
// they borrow it from their parent scope. Useful as anon functions.
// Functions with no "name"
// All arrow functions are anonymous
// Example:
function (a, b) { return (a + b); }
// Since function has no name, it must be assigned to a variable to be called.
const add = function (a, b) { return (a + b); }
Make a dynamic chain of promises
Use
arr.reduce((c, d) => c.then(() => fn(d)), Promise.resolve()).catch(error);
to convert
const arr = [d1, d2, d3, ..., dn];
function fn(d) {
return new Promise((res, rej) => { ...; res() });
}
into
Promise.resolve().then(() => fn(d1)).then(() => fn(d2)).then(() => fn(d3))...then(() => fn(dn)).catch(error)
In newer versions:
for (const d of arr) {
await fn(d);
}
Get integer part of a fraction
let fraction = 1.234;
let intPart = ~~fraction; // 1
Arrays, Iterables and Array-Likes
for-of
loop
pop
, push
etcArray.from