🧠 Ultimate JavaScript Cheat Sheet
(“Everything you wish you could cram on one page” – ES1 → ES2024)
Tip: Ctrl/⌘-F to jump to a keyword. All code is strict-mode friendly unless noted.
0 · Runtime Landscape
| Runtime | File ext. | Module type | Globals | Notes |
|---|
| Browser | .js / .mjs | ESM / classic <script> | window, document, globalThis | DOM, Web APIs |
| Node ≥ 14 | .cjs | CommonJS | global, process | require, module |
| Node ≥ 14 | .mjs or "type":"module" | ESM | same | import, export, top-level await |
| Deno | .ts /.js | ESM | globalThis | Built-in TS, secure-by-default |
1 · Syntax Primitives & Coercion
// 8 primitive types
string, number, bigint, boolean, undefined, symbol, null, // Immutable
// Note: typeof null === 'object' (legacy)
// Quick checks
Number.isNaN(val) // strict NaN check
Object.is(+0, -0) // false
0 == false // true (loose)
0 === false // false (strict)
Falsy ➜ false, 0, -0, 0n, "", null, undefined, NaN – everything else is truthy.
Explicit conversions
Number("0xFF") // 255
+"42" // 42 (unary plus)
String(123) // "123"
Boolean(obj) // true
2 · Declarations, Scope & Hoisting
| Keyword | Scope | Hoisted | Re-assign | Re-declare |
|---|
var | function / global | yes (undefined) | ✅ | ✅ |
let | block | TDZ (temporal dead zone) | ✅ | ❌ |
const | block | TDZ | value ❌ (ref ✅ for objects) | ❌ |
function f(){ console.log(a); var a=1 } // undefined
function g(){ console.log(b); let b=1 } // ReferenceError
3 · Operators Highlights
- Arithmetic:
+ - * / % **
- Assignment:
a ??= 0, a ||=, a &&=
- Bitwise:
& | ^ ~ << >> >>>
- Nullish:
var x = y ?? 'default'
- Optional-chain:
obj?.prop?.[idx]?.() (stops on null/undef)
- Destructuring defaults:
const {a=1} = obj
4 · Control Flow Nuggets
label: for (const k in obj) { break label } // rare but exists
switch (true) { case x>10: … } // boolean switch trick
try { … } catch (e) { if (e instanceof SyntaxError) … }
Loop shortcuts → break, continue, return, throw.
5 · Functions & this
function decl(){} // hoisted
const expr = function(){}; // not hoisted
const arrow = () => this; // lexical this, no prototype/arguments
const meth = { f(){…} }; // concise method
const binded = fn.bind(ctx); // permanent this
call, apply mutate this once:
sum.call(null, …args);
sum.apply(null, [a,b]);
Closures
function counter(){
let c=0;
return ()=>++c; // `c` persists
}
Generators & Iterators
function* gen(){ yield* [1,2,3] }
[...gen()] // [1,2,3]
for await (const chunk of stream){} // async iterator
6 · Objects & Meta-programming
Property descriptors
Object.defineProperty(obj,'id',{
value:1, writable:false, enumerable:true, configurable:false
});
Object.freeze(obj) ➜ deep-freeze? wrap with JSON.parse(JSON.stringify(obj)) or libs.
Symbols (well-known)
Symbol.iterator, Symbol.asyncIterator, Symbol.toStringTag, Symbol.hasInstance, Symbol.toPrimitive, etc.
Proxy & Reflect
const p = new Proxy(target,{
get(t,prop,rec){ return prop in t ? t[prop] : 42 },
});
Reflect.get(t, prop, rec); // mirror native behaviour
7 · Data Structures Beyond Arrays
| Type | Core methods | Notes |
|---|
Set | .add .has .delete .size | unique values |
Map | .set .get .has .delete .size | keys of any type |
WeakSet / WeakMap | same (object keys only) | not iterable, GC-friendly |
| TypedArrays | Int8Array, Float32Array, … | binary buffer views |
ArrayBuffer / DataView | low-level memory | basis of WebGL, WASM |
BigInt | 123n | mix with number ❌ |
8 · Class Syntax (ES2015 → 2023)
class Person {
static species='Homo'; // static field
#secret = 0; // private field
constructor(name){ this.name=name }
get info(){ return `${this.name}:${Person.species}` }
#inc(){ this.#secret++ } // private method
static { // static block (ES2022)
console.log('Class loaded');
}
}
class Dev extends Person {
constructor(n,lang){ super(n); this.lang=lang }
info(){ return super.info()+` (${this.lang})` } // override
}
9 · Modules Quick Matrix
| Feature | ESM | CommonJS |
|---|
| Import | import x from './m.js' | const x=require('./m') |
| Export | export const y=1 | module.exports = {y:1} |
| Async | top-level await (ES2022) | wrapper needed |
| Live binding | ✅ | ❌ (copy) |
__dirname | import.meta.url + path | builtin |
| Dynamic | const mod = await import(path) | require(path) |
10 · Asynchronous Patterns
Event Loop 🌀
- Call stack
- Microtasks:
Promise.then/catch/finally, queueMicrotask
- Macrotasks:
setTimeout, setInterval, requestAnimationFrame, I/O
Microtasks flush before next render/frame!
Promises Toolkit
Promise.all([p1,p2]) // fail-fast
Promise.allSettled([...])
Promise.any([...]) // ES2021, fulfill-fast
Promise.race([...])
const abort = new AbortController();
fetch(url,{signal:abort.signal});
abort.abort();
Async / Await Tips
(async()=>{
const res = await fetch(url).then(r=>r.json());
// parallel
const [a,b] = await Promise.all([getA(),getB()]);
})();
Concurrency Helpers
- Web Workers / SharedWorker / ServiceWorker
- OffscreenCanvas,
Atomics, SharedArrayBuffer
- Node
worker_threads
11 · Memory & Performance
- JS uses moving, generational GC (V8: Scavenger + Mark-Sweep + Mark-Compact)
- Avoid accidental globals, detach large arrays:
array.length = 0
- Use
WeakMap for caches, listeners
- Measure:
performance.now(), console.time() / .timeEnd()
12 · Error System
| Constructor | Typical cause |
|---|
Error | generic |
TypeError | wrong type / undefined property |
ReferenceError | unknown identifier |
RangeError | out-of-range (stack size, invalid length) |
SyntaxError | eval / Function parsing |
URIError | malformed decodeURIComponent |
AggregateError | multiple errors (e.g., Promise.any) |
13 · Standard Built-ins Snapshot
Math, Date, JSON, Intl, URL, RegExp, Promise, WeakRef, FinalizationRegistry, Error, console, fetch (DOM / Node ≥ 18).
14 · Internationalization (Intl)
new Intl.NumberFormat('de-DE',{style:'currency',currency:'EUR'}).format(1234.5)
// "1.234,50 €"
new Intl.RelativeTimeFormat('en',{numeric:'auto'}).format(-1,'day')
// "yesterday"
Intl.ListFormat, Intl.DateTimeFormat, Intl.PluralRules, Intl.Segmenter.
15 · RegExp Modern Goodies
const re = /(?<prot>https?):\/\/(?<host>[^/]+)/; // named groups
re.exec(url).groups.prot
/^\p{Emoji}+$/u // Unicode property escapes
/x(?<=\$)\d+/ // lookbehind
Flags: g global, i ignoreCase, m multiline, s dotAll, u unicode, y sticky.
16 · DOM / Web APIs Speed Tour
document.querySelector('#app').insertAdjacentHTML('beforeend','<div/>');
const onResize = new ResizeObserver(entries=>{ … }).observe(el);
localStorage.setItem('key', JSON.stringify(data));
history.pushState(state,'','/new');
window.requestIdleCallback(()=>{/* low-priority */});
APIs: Canvas, WebGL, WebSocket, WebRTC, Notifications, Fullscreen, Clipboard, IntersectionObserver, MutationObserver, Payment Request, Credentials, Streams, etc.
17 · Node-Specific Gems
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';
process.on('uncaughtException', console.error);
const __dirname = new URL('.', import.meta.url).pathname;
Tools: EventEmitter, Buffer, crypto, zlib, cluster, child_process, worker_threads.
18 · Latest ECMAScript Features (cheat timeline)
| Year | Key Additions |
|---|
| ES2015 | let/const, classes, arrow, Promise, modules, Set/Map |
| ES2016 | Array.prototype.includes, ** |
| ES2017 | async/await, Object.values/entries, shared memory |
| ES2018 | Rest/Spread for objs, Promise.finally, async iterators, regex upgrades |
| ES2019 | flat/flatMap, Object.fromEntries, optional catch binding |
| ES2020 | BigInt, ??, ?., globalThis, dynamic import |
| ES2021 | Promise.any, String.replaceAll, logical assignment, WeakRef |
| ES2022 | class fields & static blocks, at(), Error.cause, Array.prototype.findLast |
| ES2023 | Array.prototype.toSorted, toReversed, toSpliced, with, Symbol.dispose*(TC39 stage3) |
| ES2024* | Temporal, decorators, explicit resource management (stage 4 soon) |
19 · One-Liner Cookbook
// Deep clone (JSON-safe)
const copy = JSON.parse(JSON.stringify(obj));
// Shuffle
arr.sort(()=>Math.random()-0.5);
// Range [n..m]
const range = (n,m)=>Array.from({length:m-n+1},(_,i)=>n+i);
// Wait
await new Promise(r=>setTimeout(r, ms));
// Unique array
[...new Set(arr)]
// Swap vars
[a,b] = [b,a];
20 · Debug & Tooling
debugger; statement = breakpoint
- Chrome DevTools ➜ Performance tab for flame-chart
- Node:
node --inspect file.js or built-in test runner (node --test)
- Linters: ESLint, formatters: Prettier, type checker: TypeScript
💡 Final Pointers
- Prefer
const, embrace immutability.
- Use strict equality (
===) & strict mode (ES modules auto-strict).
- Batch DOM writes/reads to avoid layout thrash.
- Keep async code cancelable (
AbortController).
- Profile before optimizing – most slowdowns are I/O or needless re-renders.
Happy hacking! 🚀