JavaScript Course
JavaScript Cheatsheet
A quick, printable reference with essential modern JavaScript syntax: variables, strings, arrays, objects, functions, flow control, async/await, and ESM modules. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core JavaScript Invariants & Pitfalls to Avoid
Check these five rules before relying on runtime behavior.
- Always use === and !== instead of == and != to prevent silent type coercion bugs (e.g. 0 == "" is true).
- Remember const prevents variable reassignment, not mutation of an object or array’s inner contents.
- Array.prototype.sort() sorts lexicographically by default and mutates in-place: pass a comparator or use toSorted().
- fetch() only rejects on network failures: always inspect response.ok to catch HTTP 404/500 responses.
- Use nullish coalescing (??) rather than logical OR (||) whenever 0, "", or false are legitimate values.
1. Variables & Types
Declarations
let x = 10; // reassignable const PI = 3.14; // non-reassignable // avoid var in modern codePrefer const; choose let only when you genuinely need to reassign.
Pitfall: const locks the binding, not the value: const arr = [1]; arr.push(2) still mutates the array.
Primitive types
typeof 'hello' // 'string' typeof 42 // 'number' typeof true // 'boolean' typeof undefined // 'undefined' typeof null // 'object' (historical quirk) typeof 10n // 'bigint'Check primitive types at runtime with typeof.
Pitfall: typeof null returns "object" for historical reasons: test null explicitly with value === null and check arrays with Array.isArray(v).
Comparisons
1 === '1' // false (no coercion) 1 == '1' // true (coercion - avoid) NaN === NaN // false -> use Number.isNaN(x)Always use === / !== for predictable equality checks.
Pitfall: NaN is never equal even to itself: use Number.isNaN(x) instead of global isNaN("foo"), which coerces first.
Explicit conversions
Number('42') // 42 String(42) // '42' Boolean(0) // false parseInt('1a', 10) // 1Convert types explicitly instead of relying on implicit coercion.
Pitfall: Number("") evaluates to 0, while parseInt("12px", 10) stops before "px" and returns 12: always pass radix 10.
2. Strings & Numbers
Template literals
const name = 'World'; const msg = `Hello, ${name}!`; const multiline = `line 1 line 2`;Backticks enable ${...} interpolation and multi-line strings.
Pitfall: Using single or double quotes prints literal "${name}" instead of interpolating.
Common methods
'hello'.length // 5 'hello'.toUpperCase() // 'HELLO' ' hello '.trim() // 'hello' 'a,b,c'.split(',') // ['a', 'b', 'c'] ['a', 'b', 'c'].join('-') // 'a-b-c' 'hello'.includes('ell') // true 'hello'.slice(1, 4) // 'ell' 'abc'.replace('b', 'X') // 'aXc'Strings are immutable: every method returns a brand new string.
Pitfall: replace("b", "X") only swaps the first occurrence: use replaceAll() when replacing every match.
Numbers & Math
Math.max(1, 2, 3) // 3 Math.min(...arr) Math.round(1.6) // 2 Math.floor(1.9) // 1 Math.ceil(1.1) // 2 Math.abs(-5) // 5 (1.2345).toFixed(2) // '1.23'Core numeric helpers on Number and Math.
Pitfall: toFixed(2) returns a string rather than a number, and IEEE 754 floating-point math yields 0.1 + 0.2 !== 0.3.
3. Arrays
Create & access
const a = [1, 2, 3]; a[0] // 1 a.at(-1) // 3 a.length // 3 a.push(4) // [1, 2, 3, 4] a.pop() // removes and returns the last element a.unshift(0); a.shift();Index access and stack/queue mutations.
Pitfall: a[-1] looks up property "-1" and returns undefined: use a.at(-1) to index from the end.
Spread & copy
const b = [...a, 4, 5]; const copy = [...a]; const max = Math.max(...a);Expands iterable items into a new array or function argument list.
Pitfall: [...a] only creates a shallow copy: nested objects stay shared by reference unless cloned with structuredClone.
Functional — map / filter
[1, 2, 3].map((n) => n * 2) // [2, 4, 6] [1, 2, 3, 4].filter((n) => n % 2) // [1, 3]Transforms or selects items without mutating the source array.
Pitfall: Wrapping an arrow body in { ... } without an explicit return turns every mapped item into undefined.
Functional — reduce
[1, 2, 3, 4].reduce((acc, n) => acc + n, 0) // 10 [1, 2, 3].reduce((acc, n) => Math.max(acc, n), -Infinity) // 3Folds an array down into a single accumulated value.
Pitfall: Calling reduce on [] without an initial accumulator throws a TypeError: always supply a seed value.
Search
[1, 2, 3].find((n) => n > 1) // 2 [1, 2, 3].findIndex((n) => n > 1) // 1 [1, 2, 3].some((n) => n > 2) // true [1, 2, 3].every((n) => n > 0) // true [1, 2, 3].includes(2) // trueFinds matching items or short-circuits predicate checks.
Pitfall: [].every(...) returns true vacuously on empty arrays; includes() compares objects by reference identity.
Sorting
// In-place (mutates!) [3, 1, 2].sort((a, b) => a - b) // [1, 2, 3] // Non-destructive copy [3, 1, 2].toSorted((a, b) => b - a) // [3, 2, 1]Always pass a numeric comparator function for predictable ordering.
Pitfall: [10, 2].sort() defaults to UTF-16 string comparison ([10, 2]) and mutates the original array in place.
4. Objects
Create & access
const user = { name: 'Alice', age: 30 }; user.name // 'Alice' user['name'] // 'Alice' user.email = 'x@y'; // add property delete user.age;Use dot notation for static keys and brackets for computed keys.
Pitfall: user.key accesses the literal key "key", not the contents of variable key: write user[key].
Destructuring
const { name, age = 0 } = user; const { name: userName } = user; // rename const [first, ...rest] = [1, 2, 3];Unpacks properties or array slots with aliases and fallback defaults.
Pitfall: Default values (= 0) only trigger for undefined — an explicit null value skips the default.
Spread & merge
const user2 = { ...user, age: 31 }; // copy + override const merged = { ...a, ...b };Shallow-copies own enumerable properties; later spreads override earlier keys.
Pitfall: Nested objects are overwritten wholesale rather than recursively deep-merged.
Iteration
Object.keys(user) // ['name', 'age'] Object.values(user) // ['Alice', 30] Object.entries(user) // [['name', 'Alice'], ['age', 30]] for (const [k, v] of Object.entries(user)) { /* ... */ }Safely iterate own enumerable keys, values, or entries.
Pitfall: Avoid raw for...in loops on untrusted objects because they walk inherited prototype properties.
From/to entries
Object.fromEntries([['a', 1], ['b', 2]]) // { a: 1, b: 2 }Builds an object back from [key, value] pairs.
Pitfall: Duplicate keys in the input list silently overwrite earlier values.
5. Functions
Shapes
function add(a, b) { return a + b; } const addArrow = (a, b) => a + b; const greet = (name = 'World') => `Hello, ${name}`;Function declarations, arrow expressions, and default parameters.
Pitfall: Arrow functions capture lexical this and are not hoisted, so calling a const arrow before its declaration fails.
Rest & spread
function add(...numbers) { return numbers.reduce((a, b) => a + b, 0); } add(1, 2, 3); // 6 add(...[1, 2, 3]); // 6Collects variadic arguments or spreads an array across call parameters.
Pitfall: The rest parameter (...numbers) must always appear last in the parameter list.
Closure
function createCounter() { let count = 0; return () => ++count; } const next = createCounter(); next(); next(); next(); // 3Inner functions retain live references to variables in their enclosing lexical scope.
Pitfall: Multiple closures built inside one outer invocation share that same state variable.
Higher-order functions
const multiply = (k) => (n) => n * k; const double = multiply(2); double(5); // 10Functions returning or accepting other functions for composable logic.
Pitfall: Deeply nested currying hurts stack traces and readability when an options object is clearer.
6. Flow Control
if / else
if (x > 0) { // positive } else if (x === 0) { // zero } else { // negative } // Ternary const label = x > 0 ? 'positive' : 'non-positive';Conditional branching and concise ternary expressions.
Pitfall: Chaining nested ternary expressions quickly harms readability and hides precedence mistakes.
switch
switch (day) { case 'sat': case 'sun': return 'weekend'; default: return 'weekday'; }Compares one value against discrete cases using strict equality (===).
Pitfall: Forgetting break or return silently falls through into the next case clause.
Loops
for (let i = 0; i < n; i++) { /* ... */ } for (const v of arr) { /* values */ } for (const k in obj) { /* keys */ } while (cond) { /* ... */ } do { /* at least once */ } while (cond);for...of iterates over iterable values; for...in walks enumerable property names.
Pitfall: Never iterate arrays with for...in: it visits string indices ("0", "1") rather than values.
break / continue
for (const n of nums) { if (n < 0) continue; // skip if (n > 100) break; // exit // ... }Controls loop iteration inside for, while, and do...while.
Pitfall: Array.prototype.forEach ignores break and continue: use for...of or some/every to short-circuit.
try / catch / finally
try { const result = mayFail(); } catch (err) { console.error(err.message); } finally { // always runs, whether success or failure }Handles synchronous exceptions and guarantees cleanup in finally.
Pitfall: Returning inside finally overrides any return value or thrown error from try or catch.
7. Asynchronous
Promises
Promise.resolve(42); Promise.reject(new Error('no')); p.then((v) => console.log(v)) .catch((err) => console.error(err));Represents an eventual value or failure across async boundaries.
Pitfall: Forgetting to return the nested Promise inside .then() breaks error propagation and passes undefined.
async / await
async function loadData() { const res = await fetch('/api/data'); if (!res.ok) throw new Error('HTTP ' + res.status); return await res.json(); } const data = await loadData();await pauses an async function until the Promise settles.
Pitfall: fetch() does not reject on HTTP 404 or 500: always check res.ok before parsing JSON.
Async error handling
async function safeRead() { try { return await loadData(); } catch (err) { return null; } }Catch async rejections cleanly with try/catch around await.
Pitfall: Writing return loadData() without await inside try skips catch if the returned Promise rejects.
Combinators
Promise.all([p1, p2, p3]) // all succeed, or fail fast on first error Promise.allSettled([p1, p2, p3]) // waits for all outcomes Promise.race([p1, p2]) // first to settle winsRun independent async tasks concurrently.
Pitfall: Awaiting inside a loop forces sequential latency; switch to Promise.all or allSettled for parallel work.
8. ESM Modules
export / import
// math.js export function add(a, b) { return a + b; } export const PI = 3.14; // app.js import { add, PI } from './math.js';Named exports keep symbol names consistent across modules.
Pitfall: Native ESM requires explicit file extensions (./math.js) for relative imports; omitting braces expects a default export.
Default export
// log.js export default function log(msg) { /* ... */ } // app.js import log from './log.js';One default export per module.
Pitfall: Consumers can arbitrarily rename default imports, making cross-file refactoring harder than with named exports.
Re-export
export { add as sum } from './math.js'; export * from './utils.js';Aggregates module exports from a single entry point.
Pitfall: export * ignores default exports: re-export default symbols explicitly if callers expect them.