Below is an exhaustive, advanced JavaScript cheat sheet that goes beyond the basics, covering edge cases, lesser-known features, performance optimizations, security considerations, and emerging trends up to ES2024 and beyond. This is designed for developers aiming to master the language, including obscure syntax, interoperability, and practical insights. It's an evolution of previous versions, incorporating refinements and new details.
Master-Level JavaScript Cheat Sheet
(ES1 to ES2024+ | Advanced Insights for Pros)
Disclaimer: JavaScript evolves rapidly via TC39. This sheet covers ratified features and stage 3+ proposals. Always check MDN or TC39 for the latest. Use in strict mode for best practices.
Quick Nav: Use Ctrl/⌘-F for keywords. Code examples are concise but include edge cases.
0 · Core Concepts & Environment
Runtime & Engine Nuances
| Engine | Key Traits | Edge Cases |
|---|
| V8 (Chrome, Node) | Just-in-time (JIT) compilation, generational GC | Handles tail call optimization (TCO) inconsistently; watch for stack overflows in recursion. |
| SpiderMonkey (Firefox) | Parallel GC, WebAssembly support | Strict mode enforces more errors (e.g., undeclared globals). |
| JavaScriptCore (Safari) | AOT-like optimizations | Lacks some experimental features; test async iterators carefully. |
| Deno / Bun | Secure-by-default, built-in TypeScript | Deno uses ES modules; Bun adds ultra-fast startup but quirks with CommonJS interop. |
Global Object: globalThis (ES2020) unifies window (browser), global (Node), etc.
Edge Case: In workers, self is the global; avoid assuming window.
Strict Mode & Module Behavior
- Enable:
"use strict"; or via modules/ESM.
- Benefits: Prevents accidental globals, enforces
this as undefined in functions, and throws on invalid assignments.
- Edge: In non-strict mode,
with statement is deprecated but still works—avoid it like the plague for security.
1 · Advanced Syntax & Declarations
Variable & Function Declarations
- Temporal Dead Zone (TDZ): For
let/const, accessing before declaration throws a ReferenceError. Example:
console.log(x); // ReferenceError
let x = 10;
- Function Hoisting Quirks: Named function expressions aren't fully hoisted:
const f = function g(){}; // g is not hoisted outside this scope
- Block Scoping in Loops:
for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Logs 0,1,2 (let is block-scoped)
for (var i = 0; i < 3; i++) { ... } // Logs 3,3,3 (var leaks)
Destructuring & Rest/Spread Deep Dive
- Nested destructuring with defaults:
const [{x = 0, y = 0} = {}] = [{x: 1}]; // [ {x:1, y:0} ]
- Spread for arrays/objects with edge cases:
const merged = { ...{a:1}, ...{b:2, a:3} }; // {a:3, b:2} — last one wins
const shallowClone = [...arr]; // Doesn't deep-clone; use lodash.cloneDeep for nested objects.
2 · Operators & Expressions
Lesser-Known Operators
- Exponentiation (
**): Right-associative, e.g., 2 ** 3 ** 2 === 2 ** (3 ** 2) === 512.
- Bitwise Operators for Flags: Use for enums or permissions:
const FLAG_A = 1 << 0; // 1
const FLAG_B = 1 << 1; // 2
const combined = FLAG_A | FLAG_B; // 3
(combined & FLAG_A) === FLAG_A; // true
- Nullish Coalescing with Assignment (
??=):
let config = { timeout: null };
config.timeout ??= 5000; // Sets to 5000 if null/undefined
- Pipeline Operator (Stage 3 Proposal): For cleaner chaining:
const res = val |> fn1 |> fn2; // Equivalent to fn2(fn1(val))
Type Coercion Edge Cases
3 · Functions, Closures & Prototypes
Advanced Function Features
- Default Parameters & Destructuring:
function f({x = 0, y = 0} = {}) { return x + y; }
f(); // 0
f({x: 5}); // 5
- Tail Call Optimization (TCO): Supported in some engines for recursive functions:
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc); // Tail position
}
- Closures in Loops: Common pitfall:
const arr = [];
for (var i = 0; i < 3; i++) arr.push(() => i); // All closures capture same i
arr.map(fn => fn()); // [3,3,3]
Use: for (let i = 0; ...)
Prototypes & Inheritance Nuances
- Proto Chain Access:
Object.getPrototypeOf(obj) === SomeClass.prototype;
- Exotic Objects: Like Proxies, which can intercept proto access:
const p = new Proxy({}, { getPrototypeOf() { return null; } }); // No proto chain
4 · Objects, Classes & Meta-Objects
Property Descriptors & Proxies
- Full descriptor:
Object.defineProperties(obj, {
prop: { value: 1, writable: false, enumerable: false, configurable: true }
});
- Proxies for Validation:
const validator = new Proxy({}, {
set(target, prop, value) {
if (prop === 'age' && value < 0) throw new Error('Invalid age');
target[prop] = value;
return true;
}
});
Classes with Private & Static Enhancements
- Private fields and methods (ES2022):
class C {
#x = 10;
#method() { return this.#x; }
getX() { return this.#method(); } // Access control
}
- Static blocks for initialization:
class D {
static #privateStatic = 42;
static {
console.log(D.#privateStatic); // Runs once on class load
}
}
5 · Arrays, Iterables & Collections
Advanced Array Methods
Array.prototype.toSorted() (ES2023): Non-mutating sort.
[3,1,2].toSorted(); // [1,2,3] — original unchanged
- Custom Iterators:
class Range implements Iterable {
[Symbol.iterator]() { return { next() { /* yield values */ } };
}
for (const val of new Range(1,10)) { console.log(val); }
Sets, Maps & Weak Collections
6 · Asynchronous JavaScript & Concurrency
Event Loop & Micro/Macro Tasks
Promises & Async Patterns
Web Workers & Parallelism
7 · Modules & Interoperability
Dynamic Imports & WebAssembly
- ESM Dynamic:
const mod = await import('./module.js');
- WebAssembly Integration:
async function loadWasm() {
const { instance } = await WebAssembly.instantiateStreaming(fetch('file.wasm'));
instance.exports.add(1,2); // Call WASM function
}
8 · Error Handling & Debugging
9 · Performance & Security
- Optimizations: Minimize GC pressure; use typed arrays for binary data.
- Security: Sanitize inputs to prevent XSS:
DOMPurify.sanitize(html).
- Common Pitfalls: Prototype pollution:
Object.prototype.foo = 'bar'; can break libraries.
10 · Emerging & Experimental Features
- TC39 Stage 3+ Proposals:
- Decorators (for classes):
@decorator class C {}
- Records & Tuples: Immutable data structures.
- Import Attributes:
import json from './file.json' with { type: 'json' };
11 · Final Best Practices & Tips
- Code Smells: Avoid
eval, Function, and deep nesting.
- Testing: Use Jest for async tests; cover edge cases like NaN and infinite loops.
- Pro Tip: Profile with
performance.mark() and analyze flame graphs.
This cheat sheet is your gateway to JavaScript mastery. 🚀 Always test in multiple environments!