JavaScript Cheat Sheet
Useful JavaScript syntax and APIs.
Useful JavaScript syntax and APIs.
const pi = 3.14; // cannot be reassigned
let count = 0; // block-scoped, reassignable
function add(a, b = 0) { return a + b; } // default parameter
const square = x => x * x; // arrow function
const sum = (...nums) => nums.reduce((a, b) => a + b, 0); // rest
const { name, age = 0, ...rest } = user;
const [first, , third] = list;
const merged = { ...defaults, ...options };
const copy = [...arr, 4];
const city = user?.address?.city ?? 'unknown'; // ?. and ??
| Method | Returns | Example |
|---|---|---|
map(fn) | New array | [1,2].map(x => x * 2) → [2, 4] |
filter(fn) | New array | nums.filter(n => n > 0) |
reduce(fn, init) | One value | nums.reduce((s, n) => s + n, 0) |
find(fn) / findIndex(fn) | Item / index | users.find(u => u.id === 7) |
some(fn) / every(fn) | Boolean | arr.some(x => x == null) |
includes(v) | Boolean | ['a','b'].includes('a') |
flat() / flatMap(fn) | New array | [[1],[2]].flat() → [1, 2] |
sort((a, b) => a - b) | Same array, sorted | Without a comparator, numbers sort as strings |
toSorted(), toReversed() | New array | Non-mutating versions (ES2023) |
at(-1) | Item | Last element |
`Hello ${name}` // template literal
s.trim() s.toUpperCase() s.padStart(5, '0')
s.split(',') s.slice(0, 3) s.replaceAll('a', 'b')
s.startsWith('http') s.includes('@')
Object.keys(o) Object.values(o) Object.entries(o)
Object.fromEntries([['a', 1]]) // { a: 1 }
structuredClone(o) // deep copy
class Point {
#secret = 1; // private field
constructor(x, y) { this.x = x; this.y = y; }
get length() { return Math.hypot(this.x, this.y); }
static origin() { return new Point(0, 0); }
}
async function load(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(res.status);
return await res.json();
} catch (err) { console.error(err); }
}
const [a, b] = await Promise.all([load(u1), load(u2)]);
0.1 + 0.2 === 0.30000000000000004: floating point; round for display with toFixed().== converts types ('1' == 1 is true); use ===.typeof null === 'object' and typeof [] is 'object'; use Array.isArray().JSON.stringify drops undefined and functions, and turns NaN into null.Use const by default, let when the variable is reassigned, and avoid var, which is function-scoped and hoisted.
Paste it into the JavaScript syntax checker, which reports the engine's error without running the code.