Cheatsheets
JavaScript
Modern JavaScript: ES2020+ syntax, async/await, array methods, closures, and the gotchas.
Practice this65 entries
Variables & scope5
const PI = 3.14Block-scoped binding that can't be reassigned. Default choice.
let count = 0Block-scoped binding you intend to reassign.
var x (avoid)Legacy function-scoped binding — prefer let/const.
{ let a = 1; }Block scope — `a` does not exist outside the braces.
typeof x === 'undefined'Safe undeclared-variable check (no ReferenceError).
Destructuring, spread & rest7
const { name, age } = userObject destructuring — pull named properties into variables.
const [first, ...rest] = arrArray destructuring with a rest element collecting the remainder.
[...a, ...b] { ...o1, ...o2 }Spread — shallow-copy/merge arrays and objects.
function f(...args)Rest parameters — collect remaining arguments into a real array.
const { a = 1 } = objDefault value when the property is undefined.
function f({ id, name })Destructure a parameter object directly in the signature.
const [, , third] = arrSkip elements with empty holes.
Functions & arrow functions7
const f = (a, b) => a + bArrow function — concise syntax with a lexical (inherited) `this`.
function greet(name = 'world')Default parameter values — used when the argument is undefined.
const f = function () {}Function expression (anonymous, assigned to a variable).
function hoisted() {}Function declaration — hoisted, callable before its definition.
(() => { ... })()IIFE — immediately-invoked function expression for a private scope.
f.call(obj, a, b) f.apply(obj, [a,b])Invoke with an explicit `this` (args vs array of args).
const bound = f.bind(obj)Return a new function with `this` permanently fixed to obj.
Template literals & strings8
`Hello, ${name}!`Template literal — interpolate expressions and span multiple lines.
`line1\nline2` or real newlinesMulti-line strings without manual concatenation.
tag`Hello ${x}`Tagged template — a function processes the literal parts and values.
str.includes('x') str.startsWith('x')Substring / prefix checks returning a boolean.
str.trim() str.trimStart()Remove surrounding (or leading) whitespace.
str.padStart(4, '0')Pad to a length — e.g. '7' → '0007'.
str.replaceAll('a', 'b')Replace every occurrence (no global-regex needed).
[...str] Array.from(str)Split into characters, correctly handling surrogate pairs/emoji.
Objects, arrays, immutability & nullish access10
arr.map(fn) arr.filter(fn) arr.reduce(fn, init)The core trio — transform, select, and fold a collection without mutating it.
Object.keys / values / entries(obj)Iterate an object's own enumerable properties as arrays.
arr.find(fn) arr.findIndex(fn)Return the first matching element / its index (or undefined / -1).
arr.some(fn) arr.every(fn) arr.flatMap(fn)Any-match / all-match boolean tests; flatMap maps then flattens one level.
arr.sort((a, b) => a - b)In-place sort — provide a comparator for numbers (default is string order!).
structuredClone(obj) Object.freeze(obj)Deep clone (Maps/Dates/cycles, not functions) / shallow immutable (ignores writes).
obj?.a?.b arr?.[0]Optional chaining — short-circuit to undefined if a link is null/undefined.
a ?? bNullish coalescing — use b only when a is null or undefined.
obj?.method?.()Optional call — invoke only if the function exists, else return undefined.
obj.a ??= 1 obj.a ||= 'x' obj.a &&= yLogical assignment — set on nullish / on falsy / on truthy.
Promises, async/await & the event loop10
async function f() { await p; }async/await — write asynchronous code that reads top-to-bottom.
Promise.all([p1, p2])Run promises concurrently; resolve to an array, reject on the FIRST failure.
Promise.allSettled([...])Wait for all to finish; never rejects — each result is fulfilled or rejected.
Promise.race([...]) Promise.any([...])Settle on the first to settle / the first to FULFILL (any).
new Promise((resolve, reject) => {})Build a promise around a callback API (e.g. setTimeout, events).
p.then(onOk).catch(onErr).finally(fn)Promise chaining; finally always runs (cleanup).
Microtasks run before macrotasksPromise callbacks (microtasks) drain fully before any setTimeout (macrotask).
setTimeout(fn, ms) setInterval(fn, ms) clearTimeout(id)Schedule/cancel a macrotask once or repeatedly; ms is a minimum delay, not exact.
queueMicrotask(fn) requestAnimationFrame(fn)Run after the current task / before the next repaint.
for (const x of iterable)Iterate values of arrays, Maps, Sets, strings, generators (NOT plain objects); use for-await-of for async iterables.
Modules, classes & closures6
export const x / export default fnES modules — named exports (many) and one default export per file.
class Animal { constructor() {} }Class syntax — sugar over prototypes with fields, methods, and inheritance.
class Dog extends Animal { super() }Inheritance — call super() before using `this` in a subclass constructor.
function counter() { let n = 0; return () => ++n; }Closure — an inner function keeps access to its outer scope's variables.
static method() {} static field = xClass-level members called on the class, not instances.
get prop() {} set prop(v) {}Computed accessors that look like plain properties.
Common gotchas6
=== vs ==Always use === (strict). == coerces types and produces surprising matches.
this (binding)`this` is set by HOW a function is called, not where it's defined.
Hoisting & the TDZDeclarations move up; let/const stay in a temporal dead zone until assigned.
NaN !== NaNNaN is the only value not equal to itself — use Number.isNaN to test.
Falsy valuesfalse, 0, -0, 0n, '', null, undefined, NaN — everything else is truthy.
0.1 + 0.2 !== 0.3Floating-point math is imprecise — compare with an epsilon.
JSON & data6
JSON.stringify(value, replacer, space)Serialize a value to a JSON string; `space` pretty-prints.
JSON.parse(str, reviver)Parse a JSON string into a value; the reviver can transform entries.
const copy = structuredClone(obj)Deep clone without the JSON round-trip's lossiness.
new Map() new Set()Keyed collection (any key type) / unique-value collection.
[...new Set(arr)]De-duplicate an array in one expression.
Object.fromEntries(map)Build a plain object from a Map or [key, value] pairs.