📡 You're offline — showing cached content
New version available!
Quick Access
JavaScript Reference

JavaScript ES6+

Modern syntax, array methods, and async logic.

All Topics

Variables & Modern Syntax

let / const / var
let = block-scoped mutable. const = block-scoped immutable binding (object content can change). var = function-scoped, avoid.
Example: const PI = 3.14; let count = 0; // never use var
?. Optional chaining
Safely access deeply nested properties — returns undefined instead of throwing if any part is null.
Example: const city = user?.address?.city ?? 'Unknown';
?? Nullish coalescing
Returns right side only if left is null or undefined. Unlike ||, it doesn't treat 0 or '' as falsy.
Example: const port = config.port ?? 3000; // 0 is valid!
??= &&= ||= (Logical assign)
Assign only if the condition is met. ??= assigns if null/undefined, &&= if truthy, ||= if falsy.
Example: user.name ??= 'Anonymous'; cache ||= fetchData();
Destructuring
Unpack arrays or object properties into variables. Supports defaults, renaming, and rest.
Example: const { id, name: fullName = 'N/A', ...rest } = user;
Spread / Rest (...)
Spread expands iterables. Rest collects remaining items. Works in function params, arrays, objects.
Example: const merged = {...defaults, ...overrides}; fn(...args);
Template literals
Multi-line strings with embedded ${expressions}. Tagged templates for SQL/HTML sanitization.
Example: const sql = gfx`SELECT * FROM ${table} WHERE id = ${id}`;
Computed property names
Use expressions as object property keys with bracket notation in object literals.
Example: const key = 'name'; const obj = { [key]: 'Alice', [`${key}_upper`]: 'ALICE' };

Array Methods

.map(fn)
Returns a NEW array of same length with each element transformed. Never mutates original.
Example: const doubled = [1,2,3].map(x => x * 2); // [2,4,6]
.filter(fn)
Returns NEW array with only elements where the callback returns truthy.
Example: const adults = users.filter(u => u.age >= 18);
.reduce(fn, init)
Accumulates array to a single value — sum, groupBy, flatten, count unique, build object.
Example: const sum = [1,2,3].reduce((acc, n) => acc + n, 0);
.find() / .findIndex()
Return first matching element/index. findLast() / findLastIndex() search from end (ES2023).
Example: const admin = users.find(u => u.role === 'admin');
.flat(n) / .flatMap(fn)
flat(Infinity) fully flattens nested arrays. flatMap = map + flat(1) in one pass.
Example: [1,[2,[3]]].flat(2); // [1,2,3]
.at(-1)
Access elements from the end with negative indices. Cleaner than arr[arr.length - 1].
Example: const last = arr.at(-1); const second = arr.at(-2);
Array.from() / Array.of()
Create arrays from iterables/array-likes / create array from arguments.
Example: Array.from({length:5}, (_,i) => i+1); // [1,2,3,4,5]
.toSorted() / .toReversed()
ES2023 immutable sort/reverse — return new array without mutating the original.
Example: const sorted = arr.toSorted((a,b) => a-b); // original unchanged

Objects & Collections

Object.entries/keys/values
Convert object to array of [key,val] pairs / keys / values for iteration and transformation.
Example: Object.entries(obj).map(([k,v]) => `${k}:${v}`);
Object.fromEntries()
Convert array of [key,val] pairs back to an object — perfect after filtering entries.
Example: Object.fromEntries(Object.entries(obj).filter(([,v]) => v > 0));
Object.assign() / {...spread}
Shallow merge objects. Spread is preferred. Neither does deep clone.
Example: const config = { ...defaults, ...userConfig };
structuredClone()
True deep clone native API — handles dates, maps, sets, circular refs (unlike JSON parse/stringify).
Example: const deep = structuredClone({ a: { b: [1,2,3] } });
Map / WeakMap
Map preserves insertion order, allows any key type. WeakMap allows GC of keys (for private data).
Example: const cache = new Map(); cache.set(user, data);
Set / WeakSet
Unique value collection. Deduplicate arrays instantly: [...new Set(arr)].
Example: const unique = [...new Set([1,1,2,3])]; // [1,2,3]
Symbol()
Unique, immutable primitive — great for private-like object keys and well-known symbols.
Example: const ID = Symbol('id'); obj[ID] = 42; // non-enumerable
Proxy / Reflect
Intercept object operations (get, set, delete). Reflect provides default behavior inside handlers.
Example: new Proxy(target, { get(t,k) { log(k); return Reflect.get(t,k); } });

Async & Promises

async / await
Syntactic sugar over Promises. await pauses function execution until promise resolves.
Example: const data = await fetch(url).then(r => r.json());
Promise.all()
Run multiple promises concurrently — resolves when ALL resolve, rejects if ANY rejects.
Example: const [users, posts] = await Promise.all([getUsers(), getPosts()]);
Promise.allSettled()
Like Promise.all but NEVER rejects — returns array of {status, value/reason} for each.
Example: const results = await Promise.allSettled(requests); // handle failures individually
Promise.race() / any()
race = first to settle (resolve OR reject). any = first to RESOLVE (ignores rejections).
Example: Promise.any([fetch(url1), fetch(url2)]); // fastest successful
AbortController
Cancel pending fetch requests or any abortable async operation by signaling abort.
Example: const ctrl = new AbortController(); fetch(url, {signal: ctrl.signal}); ctrl.abort();
for await...of
Iterate over async iterables (streams, generators) — each iteration awaits the next value.
Example: for await (const chunk of stream) { process(chunk); }
async generators
async function* produces values on demand with yield — perfect for paginated API consumption.
Example: async function* paginate(url) { let page=1; while(true) yield await fetch(`${url}?page=${page++}`); }
queueMicrotask()
Schedule a microtask — runs after current script but before any macrotasks (setTimeout, I/O).
Example: queueMicrotask(() => updateUI()); // before next render tick

Classes & OOP

class / extends / super
ES6 class syntax over prototypes. extends for inheritance. super() must be first line in child constructor.
Example: class Dog extends Animal { constructor(n) { super(n); this.type='dog'; } }
#privateField
True private class fields — not accessible outside the class (unlike convention _underscore).
Example: class BankAccount { #balance = 0; deposit(n) { this.#balance += n; } }
static / static #private
Class-level method/property (not per-instance). static #private for private class-level data.
Example: class Config { static #instance; static getInstance() { return Config.#instance ??= new Config(); } }
get / set accessors
Define computed properties that look like properties but run functions on access/assignment.
Example: get fullName() { return `${this.first} ${this.last}`; }
Mixin pattern
Compose classes from multiple behaviors (JS doesn't support multiple inheritance directly).
Example: const Serializable = (Base) => class extends Base { toJSON() {...} };

DOM & Browser APIs

querySelector / querySelectorAll
CSS-selector based element selection. Returns first match / NodeList. Convert to array with [...list].
Example: const btns = [...document.querySelectorAll('.btn:not(:disabled)')];
addEventListener(type, fn, opts)
Options: { once, passive, capture }. passive:true tells browser not to wait for preventDefault (scroll perf).
Example: el.addEventListener('scroll', fn, { passive: true, once: true });
IntersectionObserver
Detect elements entering/leaving viewport — lazy loading, infinite scroll, animation triggers.
Example: new IntersectionObserver(([e]) => e.isIntersecting && loadMore(), {threshold:0.1}).observe(sentinel);
MutationObserver
Watch DOM changes (child additions, attribute changes) without polling.
Example: new MutationObserver(muts => muts.forEach(m => handle(m))).observe(el, {childList:true});
ResizeObserver
React to element size changes — more reliable than window resize for component-level layouts.
Example: new ResizeObserver(([e]) => setWidth(e.contentRect.width)).observe(el);
localStorage / sessionStorage
Persistent / tab-session key-value storage (~5MB). Always JSON.stringify complex data.
Example: localStorage.setItem('prefs', JSON.stringify(prefs)); JSON.parse(localStorage.getItem('prefs'));
Clipboard API
Async clipboard read/write. Requires user gesture and permissions-policy on site.
Example: await navigator.clipboard.writeText('Copied text!');
Web Workers
Run heavy JS off the main thread to avoid UI freezing. Communicate via postMessage.
Example: const w = new Worker('worker.js'); w.postMessage(data); w.onmessage = ({data}) => handle(data);

Patterns & Performance

Closure
Function that captures variables from outer scope even after outer function has returned.
Example: const makeCounter = (n=0) => ({ inc: () => ++n, get: () => n });
Currying / Partial application
Transform a function into a chain of single-argument functions for reusable partial application.
Example: const mul = a => b => a * b; const double = mul(2); double(5); // 10
Debounce / Throttle
Debounce delays execution until N ms after last call. Throttle limits to once per N ms.
Example: const debouncedSearch = debounce(search, 300); // wait 300ms after typing stops
Memoization
Cache function results — avoid re-computing expensive pure functions with the same arguments.
Example: const memo = fn => { const c = new Map(); return x => c.has(x) ? c.get(x) : c.set(x, fn(x)).get(x); };
requestAnimationFrame
Schedule visual updates in sync with browser repaint — smoother animations than setTimeout.
Example: const animate = t => { draw(t); requestAnimationFrame(animate); }; requestAnimationFrame(animate);
WeakRef / FinalizationRegistry
Hold object reference without preventing GC (ES2021). Registry notifies when object is collected.
Example: const ref = new WeakRef(target); ref.deref()?.doSomething();