Language :: JavaScript

JavaScript Handbook

JavaScript is a dynamic, prototype-based, single-threaded language created by Brendan Eich in 1995. It is the only language that runs natively in every browser, and with Node.js, Deno, and Bun it also runs on the server. The event loop model makes I/O-heavy workloads (APIs, chat, real-time dashboards) extremely efficient without threads. Modern JS (ES2015+) adds classes, modules, async/await, and destructuring, making it a first-class language for large applications.

Pick JavaScript when

  • You're building anything in the browser — JS is the only language that runs natively on the client. There is no alternative without a transpiler.
  • You want one language for frontend and backend — Node.js lets the same team share types, validation logic, and models between client and server. Full-stack frameworks (Next.js, Nuxt, SvelteKit) capitalise on this.
  • Real-time features — WebSockets, Server-Sent Events, and WebRTC are all JavaScript-native. Building a live chat, collaborative editor, or multiplayer game UI starts here.
  • Serverless and edge functions — Cloudflare Workers, Vercel Edge, AWS Lambda@Edge all run JS natively with near-zero cold start. The deployment model fits JS perfectly.
  • Large NPM ecosystem — over 2 million packages. UI frameworks (React, Vue, Svelte), bundlers, utilities — the ecosystem is unmatched for web development.
  • Rapid UI prototyping — JS + HTML + CSS in a browser gives instant visual feedback. No compile step, no build tool required to get started.

Think twice before choosing JavaScript when

  • Type safety is a hard requirement — plain JS has no compile-time type checking. Bugs in production caused by undefined is not a function are legendary. Use TypeScript instead for anything beyond a small script.
  • CPU-bound workloads — JS is not the right tool for video encoding, scientific computing, or cryptography. Use WebAssembly, Rust, or C++ for that layer; call it from JS if needed.
  • True multithreading — JS is single-threaded (Web Workers exist but are isolated). For parallel computation, Go, Java, or Rust are better choices.
  • Long-lived, strict codebases at scale — without TypeScript and disciplined conventions, large JS codebases become hard to maintain. Prefer TypeScript for any project that will outlive the sprint it was created in.

JavaScript vs. its closest alternatives

  • JS vs TypeScript — TypeScript is JS with types. For any project larger than a script, TypeScript will catch bugs earlier and make refactoring safer at almost zero cost. There is rarely a reason to write plain JS in 2024+.
  • JS vs Python — both are dynamically typed and interpreted. JS owns the browser and real-time web; Python owns data science and scripting. For a pure backend API either works; Node tends to handle more concurrent connections with less memory.
  • JS (Node) vs Go — Go is faster, statically typed, and has real concurrency. Node has a bigger ecosystem and requires less boilerplate for web APIs. Choose Go when performance and correctness are critical; Node when ecosystem breadth matters.

Your First Program

Install Node.js tooling using the Resources links. Save this program as hello.mjs.

The array holds two strings. Join inserts the separator between the elements, and console.log displays the resulting string.

javascript
const names = ["Ada", "Lin"];
console.log(names.join(" and "));

Run these commands from the directory containing the source file. The output is Ada and Lin

bash
node hello.mjs

Resources

Topics

Variables & Types

let allows reassignment and const prevents reassignment of the binding. Neither freezes an object, so binding stability differs from object immutability.

A const binding cannot be reassigned, but an object it refers to can still change. The operator matters for coercion: adding 3 to the string 5 concatenates to produce 53, while subtraction converts both operands to numbers and produces 2. Use Array.isArray to distinguish an array from other objects.

Declare bindings and primitive values

javascript
// Declaration
let name = 'Alice';      // block-scoped, reassignable
const PI = 3.14159;      // block-scoped, not reassignable
// var old = true;       // function-scoped — avoid

// Primitive types
let num   = 42;
let float = 3.14;
let big   = 9007199254740993n;   // BigInt
let str   = 'hello';
let bool  = true;
let nothing = null;
let undef;               // undefined
let sym = Symbol('id');

Use let when the binding will change and const when it will keep the same value or reference. The n suffix creates a BigInt.

Inspect and convert values

javascript
// Type checking
typeof 42           // 'number'
typeof 'hi'         // 'string'
typeof null         // 'object' (historical quirk)
Array.isArray([])   // true

// Type coercion
'5' + 3   // '53' — string concat
'5' - 3   // 2    — numeric coercion
!!0       // false
!!''      // false

Use Array.isArray for arrays. The plus operator concatenates when one operand is a string, while subtraction converts both operands to numbers.

Strings

Strings are immutable UTF-16 text. Template literals support interpolation, while Unicode-aware processing may require code-point or grapheme iteration.

Strings are immutable. Trim, replace, and toUpperCase return strings and leave their inputs unchanged. With a string search argument, replace changes the first match and replaceAll changes every match. Slice excludes its end index, so slicing hello from 1 to 3 produces el. Split returns an array and join inserts a separator between its elements.

Interpolate a name

javascript
const name = 'Alice';

// Template literals
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
const multiline = `
  line one
  line two
`;

Backticks allow interpolation and preserve newlines. The greeting inserts Alice between the literal text and the exclamation mark.

Search and transform strings

javascript
// Common methods
'hello'.toUpperCase()          // 'HELLO'
'  hello  '.trim()             // 'hello'
'hello world'.split(' ')       // ['hello', 'world']
['a', 'b'].join(', ')          // 'a, b'
'hello'.includes('ell')        // true
'hello'.startsWith('he')       // true
'hello'.replace('l', 'L')      // 'heLlo'
'hello'.replaceAll('l', 'L')   // 'heLLo'
'hello'.slice(1, 3)            // 'el'
'hi'.padStart(5, '0')          // '000hi'
'ha'.repeat(3)                 // 'hahaha'
Number('42')                   // 42

String operations return new values. Compare replace, which changes the first match here, with replaceAll, which changes both occurrences of l.

Control Flow

Conditions use truthiness and loops repeat work. Use explicit tests when zero or an empty string is a valid value rather than missing data.

Nullish coalescing uses the fallback for null or undefined and preserves values such as zero. Optional chaining skips a property access when its receiver is nullish, but the variable at the start of the chain must be declared. The optional-chaining line assumes a user variable supplied by the surrounding code.

Choose a branch

javascript
const x = 42;

// if / else
if (x > 100) {
  console.log('big');
} else if (x > 10) {
  console.log('medium');
} else {
  console.log('small');
}

// Ternary
const label = x % 2 === 0 ? 'even' : 'odd';

// Nullish coalescing
const port = null ?? 3000;
const safe = undefined ?? 'default';

// Optional chaining
const user = {};
const city = user?.address?.city;

// switch
switch (x % 3) {
  case 0: console.log('divisible'); break;
  case 1: console.log('rem 1');     break;
  default: console.log('rem 2');
}

With x set to 42, the conditional prints medium and the switch selects the zero remainder. Nullish operators handle missing values.

Iterate over values and keys

javascript
// Loops
for (let i = 0; i < 5; i++) { /* ... */ }
for (const item of [1, 2, 3]) { console.log(item); }
for (const key in { a: 1, b: 2 }) { console.log(key); }

// Array iteration
[1,2,3].forEach(x => console.log(x));
[1,2,3].map(x => x * 2);
[1,2,3,4].filter(x => x % 2);
[1,2,3].reduce((acc, x) => acc + x, 0);
[1,2,3].find(x => x > 1);
[1,2,3].every(x => x > 0);
[1,2,3].some(x => x > 2);

Use for of for iterable values and for in for enumerable keys. Array methods express transformations, searches and reductions directly.

Functions

Functions are values that can be passed, returned, and closed over. Defaults and rest parameters make flexible APIs possible, but inputs and results still need clear contracts.

A rest parameter gathers arguments into an array, while spread passes iterable elements as individual arguments. Each counter call creates its own count binding. The returned methods share that binding, so increment changes what value returns.

Declare functions and pass arguments

javascript
// Function declaration (hoisted)
function add(a, b) { return a + b; }

// Arrow function
const square = x => x * x;
const greet = (name, greeting = 'Hello') => `${greeting}, ${name}!`;

// Rest parameters
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}

// Spread in call
Math.max(...[1, 2, 3]);

// Destructured parameters with defaults
function createUser({ name, age = 0, role = 'user' } = {}) {
  return { name, age, role };
}

Rest collects arguments into an array, while spread expands an array into arguments at the call site.

Capture state with a closure

javascript
// Closure
function counter(start = 0) {
  let count = start;
  return {
    increment: () => ++count,
    decrement: () => --count,
    value: () => count,
  };
}

// IIFE
const result = (() => {
  const x = 42;
  return x * 2;
})();

A returned function retains access to its enclosing bindings. An IIFE runs immediately and returns its result to the surrounding expression.

Objects & Arrays

Objects store properties and arrays represent sequences. Assignment shares object references, and shallow copies retain shared nested objects.

Object spread copies enumerable own properties into a new object. Later properties override earlier ones, so updated has age 31 while person keeps age 30. The copy is shallow. For arrays, push and pop change the original, while spreading into a new array before sort keeps the original order.

Read and update object properties

javascript
const person = {
  name: 'Alice',
  age: 30,
  greet() { return `Hi, I'm ${this.name}`; },
};

// Property access
person.name;
person['age'];
person.city ?? 'unknown';   // nullish fallback

// Dynamic keys
const key = 'email';
const user = { [key]: 'alice@example.com' };

// Object methods
Object.keys(person)
Object.values(person)
Object.entries(person)
const merged = Object.assign({}, person, { age: 31 });

// Spread merge
const updated = { ...person, age: 31 };

Bracket notation evaluates the key expression. A later age property overrides the copied one in the merged object.

Manipulate arrays

javascript
// Arrays
const nums = [1, 2, 3];
nums.push(4);      // append
nums.pop();        // remove last
nums.shift();      // remove first
nums.unshift(0);   // prepend
[...nums].sort((a, b) => a - b);

// Flat
[[1,2],[3,4]].flat()              // [1,2,3,4]
[1,2,3].flatMap(x => [x, x*2])   // [1,2,2,4,3,6]

Array methods can add, remove or rearrange values. Flattening combines nested array elements to the requested depth.

Destructuring & Spread

Destructuring extracts values and spread expands or copies one level. Defaults apply to undefined, and nested references remain shared after a shallow spread.

Array patterns bind by position and object patterns bind by property name. A destructuring default applies to undefined, including a missing property. It preserves null. Rest gathers the values left over after the earlier bindings.

Unpack array positions

javascript
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];

// Skip elements
const [,, third] = [10, 20, 30];

// Default values
const [a = 0, b = 0] = [1];   // a=1, b=0

Commas skip positions, rest captures remaining elements, and a default fills a missing position.

Extract named properties and spread values

javascript
// Object destructuring
const { name, age, city = 'unknown' } = person;

// Rename on destructure
const { name: personName } = person;

// Nested
const { address: { street } } = { address: { street: '123 Main' } };

// Function parameter destructuring
function display({ name, age }) {
  console.log(`${name} is ${age}`);
}

// Spread
const arr2 = [...nums, 4, 5];
const obj2 = { ...person, role: 'admin' };

Object patterns select properties by name and can rename or nest bindings. The spread examples use nums and person from Objects and Arrays.

Classes

Classes organize constructors, methods, and inheritance over JavaScript's prototype model. Distinguish instance fields from static state and preserve invariants through methods.

The base constructor initializes shared state. A subclass constructor calls super before accessing this. An overridden method can call the base method with super and add behavior around its result.

Define an instance API

javascript
class Animal {
  #sound;   // private field (ES2022)

  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
  }

  speak() {
    return `${this.name} says ${this.#sound}`;
  }

  get label() { return `[${this.name}]`; }
  set label(v) { this.name = v.slice(1, -1); }

  static create(name, sound) {
    return new Animal(name, sound);
  }
}

The constructor initializes private state. The static factory belongs to the class.

Extend a class

javascript
class Dog extends Animal {
  constructor(name, breed) {
    super(name, 'Woof');
    this.breed = breed;
  }

  speak() {
    return super.speak() + '!';
  }
}

const dog = new Dog('Rex', 'Labrador');
dog instanceof Animal;   // true

Use Animal from the previous example. Dog calls super to initialize inherited state and extends the result of speak.

Async / Await

An async function returns a promise and await suspends that function until a result is available. Independent operations can overlap, while sequential awaits impose an order.

In this simplified example, a handler attached to an already fulfilled promise runs as a microtask after the current synchronous task finishes. It does not interrupt the current call stack.
sequenceDiagram
    participant T as Current task
    participant Q as Microtask queue
    T->>Q: Queue fulfilled promise handler
    Note over T: Remaining synchronous code runs
    T->>T: Call stack empties
    Q-->>T: Run promise handler at checkpoint

Calling an async function returns a promise. Await reads its fulfillment value or throws its rejection in the current function. Start independent operations together when neither needs the other’s result.

Create and combine promises

javascript
// Promise
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});

// Promise combinators
Promise.all([p1, p2, p3])       // all must resolve
Promise.allSettled([p1, p2])    // wait for all
Promise.race([p1, p2])          // first to settle
Promise.any([p1, p2])           // first to resolve

A promise settles once. The combinator determines whether the caller waits for all results, all settlements or the first qualifying result.

Await responses and start requests together

javascript
// async / await
async function fetchUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error('Failed:', err);
    throw err;
  }
}

// Parallel fetches
async function loadAll(ids) {
  return Promise.all(ids.map(id => fetchUser(id)));
}

Await suspends the async function. Starting independent requests together lets their waiting times overlap.

Modules (ESM)

ES modules declare imports and exports with module scope. Exported bindings can reflect updates made by the exporting module.

Save each labeled fragment in its own file. Named imports match the exported name, while a default import can use a local name chosen by the caller. Use an ES module environment for the entry file.

Export and import a module

javascript
// --- math.js ---
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }

// --- main.js ---
import Calculator, { PI, add } from './math.js';
import * as math from './math.js';

Place the declarations and the consumer in the two files indicated. The consumer can use both named and default exports.

Load on demand or forward exports

javascript
// Dynamic import (lazy loading)
const { add } = await import('./math.js');

// Re-export
export { add } from './math.js';
export * from './math.js';

Dynamic import resolves to a module namespace. A re-export exposes a binding through another module.

DOM Basics

The DOM represents documents as node trees. Query elements, change text or attributes, and attach listeners while accounting for absent or removed nodes.

Run the fragments in a browser with matching HTML elements. QuerySelector returns null if no element matches. Check the result before reading a property or attaching a listener.

Select and create elements

javascript
// Selecting elements
const el = document.querySelector('#myId');
const els = document.querySelectorAll('.myClass');

// Modifying elements
el.textContent = 'Hello';
el.innerHTML = '<strong>Bold</strong>';
el.setAttribute('data-value', '42');
el.classList.add('active');
el.classList.toggle('hidden');
el.style.color = 'red';

// Creating elements
const div = document.createElement('div');
div.textContent = 'New element';
document.body.appendChild(div);

Use this fragment on a page with the matching elements. The new div becomes visible after insertion into the document.

Handle and dispatch events

javascript
// Events
el.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('Clicked!', event.target);
});

// Custom events
el.dispatchEvent(new CustomEvent('my-event', { detail: { value: 42 } }));
el.addEventListener('my-event', e => console.log(e.detail));

Register a listener on the selected element. The custom event carries application data in its detail property.

Iterators & Generators

Iterators yield successive values and generators implement that protocol with yield. Lazy production lets callers stop before computing a complete sequence.

An iterable creates an iterator through Symbol.iterator. Each next call advances the iterator and returns a value plus a done flag. A generator supplies that protocol and pauses at each yield.

Implement the iteration protocol

javascript
// Iterator protocol: object with next() returning { value, done }
function makeRangeIterator(start, end) {
  let current = start;
  return {
    next() {
      return current <= end
        ? { value: current++, done: false }
        : { value: undefined, done: true };
    },
  };
}

// Custom iterable (implements [Symbol.iterator])
const range = {
  from: 1,
  to: 5,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

for (const n of range) { console.log(n); }   // 1 2 3 4 5
const arr = [...range];                        // [1, 2, 3, 4, 5]

Each next call returns a value and a completion flag. The range exposes an iterator so spread can collect its values.

Yield values from generators

javascript
// Generator function — pauseable with yield
function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fib = fibonacci();
fib.next().value;   // 0
fib.next().value;   // 1
fib.next().value;   // 1

// yield* delegates to another iterable
function* concat(...iters) {
  for (const it of iters) yield* it;
}
[...concat([1, 2], [3, 4])];   // [1, 2, 3, 4]

// Async generator + for await...of
async function* paginate(url) {
  let page = 1;
  while (true) {
    const res = await fetch(`${url}?page=${page}`);
    const data = await res.json();
    if (!data.length) return;
    yield data;
    page++;
  }
}

for await (const items of paginate('/api/items')) {
  console.log(items);
}

Yield pauses execution until the next request. An async generator also lets the consumer wait for values with for await of.

Symbols & Well-known Symbols

Symbols create unique property keys. Well-known symbols connect objects to language protocols such as iteration.

Two calls to Symbol with the same description create different keys. Symbol.for looks up a shared key. A well-known symbol such as Symbol.iterator lets a built-in operation discover custom behavior.

Create and share symbol keys

javascript
// Symbol() — always unique
const id1 = Symbol('id');
const id2 = Symbol('id');
id1 === id2;   // false

// Symbol.for() — shared global registry
const shared = Symbol.for('app.token');
Symbol.for('app.token') === shared;   // true
Symbol.keyFor(shared);                 // 'app.token'

// Symbol as unique object key (never clashes with string keys)
const SECRET = Symbol('secret');
const obj = { name: 'Alice', [SECRET]: 'top-secret' };
Object.keys(obj);           // ['name']  — symbol not enumerated
obj[SECRET];                // 'top-secret'

Two fresh symbols with the same description remain distinct. Symbol.for retrieves the registry entry for a shared key.

Customize built-in protocols

javascript
// Symbol.iterator — make any object iterable
class Range {
  constructor(from, to) { this.from = from; this.to = to; }
  [Symbol.iterator]() {
    let n = this.from;
    const to = this.to;
    return { next: () => n <= to ? { value: n++, done: false } : { done: true } };
  }
}
[...new Range(1, 3)];   // [1, 2, 3]

// Symbol.toPrimitive — control type coercion
const money = {
  amount: 42,
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') return this.amount;
    if (hint === 'string') return `$${this.amount}`;
    return this.amount;
  },
};
+money;        // 42
`${money}`;   // '$42'

// Symbol.hasInstance — customise instanceof
class EvenNumber {
  static [Symbol.hasInstance](n) { return Number.isInteger(n) && n % 2 === 0; }
}
4 instanceof EvenNumber;   // true
3 instanceof EvenNumber;   // false

// Symbol.toStringTag — customise Object.prototype.toString
class MyCollection {
  get [Symbol.toStringTag]() { return 'MyCollection'; }
}
Object.prototype.toString.call(new MyCollection());   // '[object MyCollection]'

Well-known symbols let an object supply behavior for iteration, primitive conversion, instance checks and display tags.

Proxy & Reflect

Proxies intercept object operations through traps. Reflect provides corresponding default operations, helping handlers preserve object invariants.

A trap runs when code performs the corresponding operation on the proxy. Forwarding with Reflect preserves the default operation and its receiver, which matters when a getter uses this.

Intercept property operations

javascript
// Basic Proxy: intercept property access
const handler = {
  get(target, prop, receiver) {
    console.log(`get: ${prop}`);
    return Reflect.get(target, prop, receiver);
  },
  set(target, prop, value, receiver) {
    console.log(`set: ${prop} = ${value}`);
    return Reflect.set(target, prop, value, receiver);
  },
  has(target, prop) {
    console.log(`has: ${prop}`);
    return Reflect.has(target, prop);
  },
  deleteProperty(target, prop) {
    console.log(`delete: ${prop}`);
    return Reflect.deleteProperty(target, prop);
  },
};

const target = { x: 1, y: 2 };
const proxy = new Proxy(target, handler);
proxy.x;          // logs 'get: x', returns 1
proxy.z = 3;      // logs 'set: z = 3'
'x' in proxy;     // logs 'has: x'

A proxy trap runs when code accesses the wrapper. Reflect forwards the operation with the original receiver where needed.

Validate writes and intercept calls

javascript
// Validation proxy
function createValidated(schema) {
  return new Proxy({}, {
    set(obj, prop, value) {
      if (schema[prop] && typeof value !== schema[prop]) {
        throw new TypeError(`${prop} must be ${schema[prop]}`);
      }
      obj[prop] = value;
      return true;
    },
  });
}
const person = createValidated({ name: 'string', age: 'number' });
person.name = 'Alice';   // ok
// person.age = 'old';  // throws TypeError

// Function proxy: intercept apply and construct
const logged = new Proxy(Math.max, {
  apply(fn, thisArg, args) {
    console.log(`called with ${args}`);
    return Reflect.apply(fn, thisArg, args);
  },
});
logged(1, 2, 3);   // logs 'called with 1,2,3', returns 3

// Reflect.ownKeys — all own keys including symbols
const sym = Symbol('s');
const o = { a: 1, [sym]: 2 };
Reflect.ownKeys(o);   // ['a', Symbol(s)]

The schema checks incoming assignments, while an apply trap observes function calls. Reflect.ownKeys includes symbol keys.

WeakMap, WeakSet & WeakRef

Weak references do not keep targets alive solely through the reference. Garbage-collection timing is unpredictable, so these APIs must not own essential cleanup or correctness.

Weak collections do not keep their keys alive by themselves. A weak reference can stop yielding an object after collection. Treat cleanup callbacks as optional because their timing is outside the program’s control.

Associate metadata with objects

javascript
// WeakMap: keys are weakly held (GC eligible when no other ref)
// Use case 1: private data per instance
const _private = new WeakMap();
class Counter {
  constructor() { _private.set(this, { count: 0 }); }
  increment() { _private.get(this).count++; }
  value() { return _private.get(this).count; }
}

// Use case 2: caching computed results without leaking memory
const cache = new WeakMap();
function expensiveProcess(obj) {
  if (cache.has(obj)) return cache.get(obj);
  const result = JSON.stringify(obj).length;   // placeholder
  cache.set(obj, result);
  return result;
}

// WeakSet: track objects without preventing garbage collection
const seen = new WeakSet();
function processOnce(obj) {
  if (seen.has(obj)) return;
  seen.add(obj);
  console.log('processing', obj);
}

WeakMap stores per-object data and WeakSet records membership without keeping those objects alive.

Observe optional liveness

javascript
// WeakRef: hold a weak reference to an object
let bigData = { payload: new Array(1e6).fill(0) };
const ref = new WeakRef(bigData);

bigData = null;   // allow GC
// later...
const data = ref.deref();   // may be undefined after GC
if (data) { console.log('still alive'); }

// FinalizationRegistry: callback when object is collected
const registry = new FinalizationRegistry((heldValue) => {
  console.log(`${heldValue} was collected`);
});

let obj = { id: 1 };
registry.register(obj, 'obj#1');
obj = null;   // eligible for GC — callback fires eventually

// Key difference vs Map/Set:
// Map/Set hold strong refs → prevent GC
// WeakMap/WeakSet hold weak refs → allow GC when no other ref exists

Handle an absent deref result. Finalization callbacks depend on garbage collection timing and may never run.

Error Handling Patterns

Throw failures with useful context and catch them where recovery is meaningful. Handle promise rejections too, and use finally for cleanup on either outcome.

An Error subclass can carry details for a particular failure. Catch at a point where the program can recover or add context, and retain the original error as the cause when wrapping it.

Attach context to errors

javascript
// Custom Error subclasses
class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'AppError';
    this.code = code;
  }
}
class NetworkError extends AppError {
  constructor(message, statusCode) {
    super(message, 'NETWORK_ERROR');
    this.name = 'NetworkError';
    this.statusCode = statusCode;
  }
}

// Error chaining with cause (ES2022)
try {
  JSON.parse('bad json');
} catch (original) {
  throw new Error('Config file is corrupt', { cause: original });
}

// AggregateError — multiple errors at once
const errors = [new Error('e1'), new Error('e2')];
throw new AggregateError(errors, 'Multiple failures');

A subclass identifies the error category, cause retains the original failure, and AggregateError carries several errors together.

Represent expected failures and catch rejections

javascript
// Type-safe result pattern (no exceptions for expected failures)
function divide(a, b) {
  if (b === 0) return { ok: false, error: 'Division by zero' };
  return { ok: true, value: a / b };
}
const result = divide(10, 0);
if (!result.ok) { console.error(result.error); }
else { console.log(result.value); }

// Promise rejection vs thrown error in async functions
async function risky() {
  throw new Error('sync throw inside async');   // becomes rejection
}
risky().catch(err => console.error(err.message));

// Unhandled rejection handling (global safety net)
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
  event.preventDefault();   // suppress default console warning
});

The caller can inspect a result object directly. A throw inside an async function becomes a rejected promise that the caller must handle.

Design Patterns

Patterns name recurring ways to coordinate functions and objects. Choose them to solve a concrete collaboration problem rather than adding structure for its own sake.

Look at who owns state in each fragment. The module pattern keeps state in a closure and exposes only selected operations. This lets callers use the state without gaining direct access to its binding.

Encapsulate state and broadcast changes

javascript
// 1. Module pattern — private state via closure
const counter = (() => {
  let _count = 0;
  return {
    increment() { _count++; },
    decrement() { _count--; },
    value() { return _count; },
  };
})();

// 2. Observer / event emitter
class EventEmitter {
  #listeners = new Map();
  on(event, fn) {
    if (!this.#listeners.has(event)) this.#listeners.set(event, []);
    this.#listeners.get(event).push(fn);
    return () => this.off(event, fn);
  }
  off(event, fn) {
    const fns = this.#listeners.get(event) ?? [];
    this.#listeners.set(event, fns.filter(f => f !== fn));
  }
  emit(event, ...args) {
    (this.#listeners.get(event) ?? []).forEach(fn => fn(...args));
  }
}

// 3. Singleton
const db = (() => {
  let instance;
  return { getInstance: () => (instance ??= { connected: false }) };
})();

A closure can hide mutable state, an emitter notifies subscribers, and a singleton exposes a shared instance.

Construct and compose behavior

javascript
// 4. Factory function vs class (factory avoids new / prototype chain)
function createUser(name, role = 'user') {
  return { name, role, greet() { return `Hi, I'm ${name}`; } };
}

// 5. Mixin — compose behaviour without inheritance
const Serializable = (Base) => class extends Base {
  serialize() { return JSON.stringify(this); }
};
class Point { constructor(x, y) { this.x = x; this.y = y; } }
class SerializablePoint extends Serializable(Point) {}

// 6. Command pattern — encapsulate operations for undo/redo
function makeTextEditor() {
  let text = '';
  const history = [];
  return {
    execute(cmd) { history.push(cmd); cmd.execute(); },
    undo() { history.pop()?.undo(); },
    getText() { return text; },
    insertCmd(str) {
      return {
        execute() { text += str; },
        undo() { text = text.slice(0, -str.length); },
      };
    },
  };
}

A factory constructs values, a mixin adds behavior to a class, and a command packages an operation with its reversal.

Performance Tips

Measure the slow interaction before optimizing. Reduce unnecessary computation and DOM updates first; caching adds memory and invalidation responsibilities.

A DOM write can invalidate layout. Reading geometry immediately afterward may force a layout calculation, so group geometry reads before writes when updating many elements. Measure the result in the browser.

Schedule and batch browser work

javascript
// 1. Avoid layout thrashing — batch reads then writes
// Bad: interleaved read/write forces repeated reflow
// el.style.left = el.offsetLeft + 1 + 'px';  // read then write in loop

// Good: read all first, then write all
const positions = elements.map(el => el.offsetLeft);
elements.forEach((el, i) => { el.style.left = positions[i] + 1 + 'px'; });

// 2. DocumentFragment — batch DOM insertions
const frag = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const li = document.createElement('li');
  li.textContent = `Item ${i}`;
  frag.appendChild(li);
}
list.appendChild(frag);   // single reflow

// 3. requestAnimationFrame — sync animations to display refresh
function animate(timestamp) {
  el.style.transform = `translateX(${timestamp * 0.1 % 300}px)`;
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

// 4. requestIdleCallback — defer non-urgent work
requestIdleCallback((deadline) => {
  while (deadline.timeRemaining() > 0 && tasks.length) {
    tasks.shift()();
  }
}, { timeout: 2000 });

// 5. IntersectionObserver — lazy load without scroll events
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
}, { rootMargin: '100px' });
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));

Batch layout reads before writes. Use frame, idle and visibility callbacks according to when the work needs to run.

Choose data structures and task queues

javascript
// 6. structuredClone vs JSON round-trip
const clone = structuredClone(obj);   // handles Date, Map, Set, undefined
// JSON.parse(JSON.stringify(obj))    // loses Date, Map, Set, undefined

// 7. Object.create(null) — pure dictionary (no prototype overhead)
const dict = Object.create(null);
dict['key'] = 'value';
'toString' in dict;   // false — no inherited keys

// 8. WeakMap to avoid memory leaks
const cache = new WeakMap();   // entries GC'd when key object is collected
// Map would keep keys alive indefinitely

// 9. Microtask vs macrotask ordering
setTimeout(() => console.log('macrotask'), 0);
Promise.resolve().then(() => console.log('microtask'));
queueMicrotask(() => console.log('microtask 2'));
// order: microtask, microtask 2, macrotask

Choose cloning and key storage based on value types and ownership. Queued microtasks run before the timer callback in this example.

Closures & Scope

A closure is a function paired with its lexical environment — the variables in scope at the time of definition, not execution. Closures enable data encapsulation, the module pattern, partial application, and memoization.

A closure retains access to a binding even after the outer function returns. A loop declared with let creates a fresh binding per iteration, so callbacks can observe the value for their own iteration.

Keep state between calls

javascript
// Closure — a function that captures its surrounding lexical scope
function makeCounter(start = 0) {
    let count = start;           // captured in the closure
    return {
        increment() { return ++count; },
        decrement() { return --count; },
        value()     { return count; },
    };
}

const counter = makeCounter(10);
counter.increment();  // 11
counter.increment();  // 12
counter.decrement();  // 11

The returned counter closes over its own state, so successive calls see the previous increment.

Control what callbacks capture

javascript
// Classic loop-variable capture bug (var) vs. fix (let / IIFE)
// Bug: all callbacks share the same `i`
for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 0);  // logs 3 3 3
}

// Fix 1: let — each iteration gets its own binding
for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 0);  // logs 0 1 2
}

// Fix 2: IIFE — create a new scope per iteration
for (var i = 0; i < 3; i++) {
    (function(j) {
        setTimeout(() => console.log(j), 0);
    })(i);
}

// Module pattern — private state via closure
const store = (function() {
    let _state = {};
    return {
        get: (k) => _state[k],
        set: (k, v) => { _state[k] = v; },
    };
})();

// Memoize — cache results using closure
function memoize(fn) {
    const cache = new Map();
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        const result = fn.apply(this, args);
        cache.set(key, result);
        return result;
    };
}

A var loop shares one binding. Let and an IIFE give each callback a separate value, while other closures deliberately share private state or a cache.

Event Loop & Microtasks

JavaScript is single-threaded. The event loop processes one task at a time: it runs all synchronous code, drains the microtask queue (Promises, queueMicrotask) completely, then picks the next macrotask (setTimeout, I/O). Long synchronous work blocks everything — break it into chunks.

Synchronous code finishes before queued promise callbacks run. The runtime drains microtasks at its checkpoint before taking another task, so a zero-delay timer can run after a promise callback queued in the same turn.

Trace task and microtask order

javascript
// JavaScript is single-threaded with a cooperative event loop.
// Execution order: synchronous → microtasks → macrotasks (tasks)

console.log('1 sync');

setTimeout(() => console.log('4 macrotask'), 0);  // task queue

Promise.resolve().then(() => console.log('2 microtask'));
queueMicrotask(()  => console.log('3 microtask'));

console.log('1 sync end');
// Output: '1 sync'  →  '1 sync end'  →  '2 microtask'  →  '3 microtask'  →  '4 macrotask'

// Microtask queue drains completely before the next macrotask
Promise.resolve()
  .then(() => { console.log('A'); return Promise.resolve(); })
  .then(() => console.log('B'));
Promise.resolve().then(() => console.log('C'));
// A → C → B   (each .then enqueues the next microtask at the tail)

Synchronous statements finish first. A microtask queued by another microtask goes to the end of the queue, which explains the A, C, B order.

Yield time to the browser

javascript
// requestAnimationFrame — fires before the next paint (between tasks)
requestAnimationFrame(() => console.log('before paint'));

// Long tasks block the event loop — break them up
function processChunk(items, index = 0) {
    const CHUNK = 100;
    for (let i = index; i < Math.min(index + CHUNK, items.length); i++) {
        // process items[i]
    }
    if (index + CHUNK < items.length) {
        setTimeout(() => processChunk(items, index + CHUNK), 0);  // yield
    }
}

// scheduler.postTask (modern browsers) — prioritised tasks
// scheduler.postTask(() => heavyWork(), { priority: 'background' });

Schedule visual work before a paint and break long work into chunks so other tasks get a chance to run.

Regular Expressions

Regular expressions in JavaScript use the RegExp object or literal /pattern/flags syntax. Named capture groups, lookbehind assertions, and matchAll were added in ES2018.

A literal provides a fixed pattern and a constructor can build one from text. When passing a pattern as a string, account for both JavaScript string escaping and regex escaping. Check for a missing match before reading captures.

Find matches and extract captures

javascript
// Literal syntax and constructor
const re1 = /hello/i;           // case-insensitive
const re2 = new RegExp('hello', 'i');

// Flags: g (global), i (ignore case), m (multiline), s (dotAll), u (unicode), d (indices)

// test — true/false
/^\d+$/.test('123');        // true
/^\d+$/.test('12x');        // false

// match — returns array or null
'hello world'.match(/\w+/g);   // ['hello', 'world']
'2024-07-15'.match(/(\d{4})-(\d{2})-(\d{2})/);
// index 0: full match, 1: '2024', 2: '07', 3: '15'

// matchAll — iterator of all matches with capture groups
const str = 'key1=val1 key2=val2';
for (const m of str.matchAll(/(\w+)=(\w+)/g)) {
    console.log(m[1], m[2]);   // key1 val1 / key2 val2
}

Use test for a boolean and match or matchAll when the matched text and groups matter.

Rewrite and split text

javascript
// replace / replaceAll
'hello world'.replace(/o/g, '0');          // 'hell0 w0rld'
'2024-07-15'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');  // '15/07/2024'

// Named groups (ES2018)
const { year, month, day } =
    '2024-07-15'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/).groups;

// Lookahead and lookbehind
/\d+(?= dollars)/.exec('100 dollars');   // '100'  (positive lookahead)
/(?<=\$)\d+/.exec('$99');               // '99'   (positive lookbehind)

// split with capturing group
'a1b2c'.split(/(\d)/);   // ['a', '1', 'b', '2', 'c']

Replacement rewrites matches. Named groups label captured text, and a capturing group in split retains separators in the result.

Web Workers

Web Workers run JavaScript on a background thread without blocking the main thread. Communication uses postMessage / onmessage with structured-clone serialization. SharedArrayBuffer + Atomics enable true shared memory between threads.

Put the main script and worker in the files indicated by the example and serve them in a browser. The worker computes separately and sends its result as a message. The main thread handles that message and owns the DOM.

Exchange messages with a worker

javascript
// ── main.js ──────────────────────────────────────────────────────────────
const worker = new Worker('./worker.js');

// Send data to worker (structured clone — no shared memory by default)
worker.postMessage({ cmd: 'compute', data: [1, 2, 3, 4, 5] });

worker.onmessage = (e) => console.log('result:', e.data);
worker.onerror   = (e) => console.error(e.message);

// Terminate when done
// worker.terminate();

// ── worker.js ─────────────────────────────────────────────────────────────
self.onmessage = (e) => {
    const { cmd, data } = e.data;
    if (cmd === 'compute') {
        const sum = data.reduce((a, b) => a + b, 0);
        self.postMessage(sum);
    }
};

Put the main and worker fragments in separate files. The worker receives a copy of the message and can respond without blocking the page.

Coordinate shared memory

javascript
// ── Shared memory with SharedArrayBuffer ──────────────────────────────────
// Requires COOP/COEP headers: Cross-Origin-Opener-Policy: same-origin
//                             Cross-Origin-Embedder-Policy: require-corp
const sab    = new SharedArrayBuffer(4);       // 4 bytes
const shared = new Int32Array(sab);            // typed view
worker.postMessage({ sab });

// In worker.js — Atomics: thread-safe operations on shared memory
// self.onmessage = ({ data: { sab } }) => {
//     const arr = new Int32Array(sab);
//     Atomics.add(arr, 0, 1);             // atomic increment
//     Atomics.notify(arr, 0, 1);          // wake up any Atomics.wait
// };

// Atomics.wait (worker) / Atomics.waitAsync (main thread, non-blocking)
// Atomics.wait(shared, 0, 0);   // block until shared[0] !== 0

In a cross-origin isolated page, share the buffer with a worker and use Atomics to update and coordinate access to its cells.

Intl API

The Intl API provides locale-aware formatting for numbers, dates, relative times, lists, and plurals. It is built into every modern runtime — no library needed.

Use a locale and options to choose display conventions. Number and date formatting produce strings for readers, so keep the original values for arithmetic and comparisons.

Format values for a locale

javascript
// Intl.NumberFormat
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
usd.format(1234567.89);   // '$1,234,567.89'

const pct = new Intl.NumberFormat('en', { style: 'percent', maximumFractionDigits: 1 });
pct.format(0.1234);       // '12.3%'

// Intl.DateTimeFormat
const df = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'full', timeStyle: 'short' });
df.format(new Date());    // 'lundi 15 juillet 2024 à 14:30'

// Intl.RelativeTimeFormat
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day');    // 'yesterday'
rtf.format(2, 'week');    // 'in 2 weeks'

// Intl.ListFormat
const lf = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
lf.format(['Alice', 'Bob', 'Charlie']);  // 'Alice, Bob, and Charlie'

Choose a locale and formatting options for money, dates, relative times and lists. The display can also depend on the runtime time zone.

Sort, pluralize and segment text

javascript
// Intl.Collator — locale-aware string sorting
const words = ['résumé', 'apple', 'éclair', 'banana'];
words.sort(new Intl.Collator('fr').compare);
// ['apple', 'banana', 'éclair', 'résumé']

// Intl.PluralRules — choose the right plural form
const pr = new Intl.PluralRules('en-US');
pr.select(0);   // 'other'
pr.select(1);   // 'one'
pr.select(2);   // 'other'

// Intl.Segmenter (ES2022) — split by grapheme, word, or sentence
const seg = new Intl.Segmenter('en', { granularity: 'word' });
[...seg.segment('Hello world!')].map(s => s.segment);
// ['Hello', ' ', 'world', '!']

A collator orders locale-sensitive strings. Plural rules return categories, and the segmenter produces text boundaries.

Prototype Chain

Every JavaScript object has an internal [[Prototype]] link to another object (or null). Property lookup traverses this chain until the property is found or the chain ends. class syntax is syntactic sugar over the same prototype mechanism.

Property lookup checks the object first and then follows its prototype links. Assigning an own property can shadow an inherited one. Use Object.hasOwn when only directly defined properties should count.

Trace inherited property lookup

javascript
// Every object has an internal [[Prototype]] link.
// Property lookup walks the chain until null is reached.

const animal = {
  breathe() { return 'breathing'; },
};
const dog = Object.create(animal);   // dog.__proto__ === animal
dog.bark = function() { return 'woof'; };

dog.bark();     // own property — found immediately
dog.breathe();  // not own — found on animal via prototype chain

// Object.getPrototypeOf is the spec-safe way to read [[Prototype]]
Object.getPrototypeOf(dog) === animal;   // true

// Constructor functions and .prototype
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() { return 'Hi, I\'m ' + this.name; };

const alice = new Person('Alice');
alice.greet();   // found on Person.prototype

// hasOwnProperty vs in
alice.hasOwnProperty('name');   // true
alice.hasOwnProperty('greet');  // false — lives on prototype
'greet' in alice;               // true  — checked up the chain

An object can find a method on its prototype. The in operator sees inherited properties, while an own-property check only sees local ones.

Build objects with different prototypes

javascript
// Class syntax desugars to the same prototype mechanism
class Vehicle {
  constructor(make) { this.make = make; }
  describe() { return 'Vehicle: ' + this.make; }
}
class Car extends Vehicle {
  constructor(make, model) {
    super(make);
    this.model = model;
  }
  describe() { return super.describe() + ' ' + this.model; }
}

const c = new Car('Toyota', 'Camry');
Object.getPrototypeOf(c) === Car.prototype;           // true
Object.getPrototypeOf(Car.prototype) === Vehicle.prototype;  // true

// Object.create(null) — no prototype at all (pure hash map)
const map = Object.create(null);
'toString' in map;   // false

// Mixin pattern — copy methods without deep inheritance
const Flyable = {
  fly() { return this.name + ' is flying'; },
};
Object.assign(Car.prototype, Flyable);
c.fly();   // 'Toyota is flying'

Class methods use the prototype chain. A null-prototype dictionary has no inherited keys, and a mixin copies methods onto a target.

this & Binding

this is not lexically scoped — it is resolved at call time based on how a function is invoked: implicit (dot notation), explicit (call/apply/bind), new, or default. Arrow functions are the exception: they capture this from the surrounding lexical scope and cannot be rebound.

A method called through an object receives that object as this. Extracting the method changes the call form and can lose the receiver. Bind makes a callable with a fixed receiver, while an arrow captures this from its surrounding scope.

Determine the receiver at the call site

javascript
// 'this' is determined at call time, not definition time (except arrows).

// 1. Implicit binding — the object left of the dot
const obj = {
  name: 'obj',
  greet() { return 'Hello from ' + this.name; },
};
obj.greet();   // 'Hello from obj'

// 2. Explicit binding — call / apply / bind
function greet(greeting) { return greeting + ', ' + this.name; }
greet.call({ name: 'Alice' }, 'Hi');        // 'Hi, Alice'
greet.apply({ name: 'Bob' }, ['Hey']);       // 'Hey, Bob'
const greetAlice = greet.bind({ name: 'Alice' });
greetAlice('Hi');                            // 'Hi, Alice'

// 3. new binding — `this` is the newly created object
function User(name) { this.name = name; }
const u = new User('Carol');   // u.name === 'Carol'

// 4. Default binding — global (or undefined in strict mode)
// function loose() { return this; }   // window in browser, undefined strict

Method calls use their receiver, call and apply supply it explicitly, and new creates a receiver for the constructor.

Preserve a receiver in callbacks

javascript
// 5. Arrow functions — lexical `this`, cannot be rebound
class Timer {
  constructor() { this.ticks = 0; }
  start() {
    // Arrow captures `this` from start()'s context
    this.interval = setInterval(() => { this.ticks++; }, 1000);
  }
  stop() { clearInterval(this.interval); }
}

// 6. Losing `this` — common mistake with callbacks
class Logger {
  constructor(prefix) { this.prefix = prefix; }
  log(msg) { console.log(this.prefix + msg); }
  attach(btn) {
    // btn.addEventListener('click', this.log);       // `this` lost
    btn.addEventListener('click', this.log.bind(this));  // fixed
    btn.addEventListener('click', (e) => this.log(e.type)); // arrow fix
  }
}

// 7. Getter / setter `this`
const rect = {
  width: 10,
  height: 5,
  get area() { return this.width * this.height; },
};
rect.area;   // 50

An arrow captures the surrounding this. When passing a method as a callback, bind it or call it through its object inside a wrapper.

Functional Programming

Functional programming builds results by applying small functions to data. Each example below runs independently. Save one as functional.js and run node functional.js. The comments beside the logging calls show the expected output.

Pure functions

A pure function returns the same result for the same inputs and has no observable side effects. Reading a variable that can change makes the result depend on hidden state. Pass the rate explicitly and let the caller decide when to print the result.

javascript
let rate = 2;
const fromState = amount => amount * rate;
const calculate = (amount, multiplier) => amount * multiplier;

console.log(fromState(5), calculate(5, 2)); // 10 10
rate = 3;
console.log(fromState(5), calculate(5, 2)); // 15 10

Changing the rate affects the first function. The second still returns 10 because both arguments are the same.

Immutable updates

When callers share data, return a new value so they can keep using the original. Array spread copies elements, and object spread copies enumerable own properties. Both copies are shallow.

javascript
const scores = [1, 2, 3];
const nextScores = [...scores, 4];

const user = { name: 'Ada', preferences: { theme: 'light' } };
const renamed = { ...user, name: 'Grace' };
const updated = {
  ...user,
  preferences: { ...user.preferences, theme: 'dark' },
};

console.log(scores.length, nextScores.length); // 3 4
console.log(renamed.preferences === user.preferences); // true
console.log(user.preferences.theme, updated.preferences.theme); // light dark

Later properties override earlier ones. The rename shares the preferences object. Changing the theme requires copying both the user and the preferences along the path to that property.

Higher-order functions

A higher-order function takes a function as an argument or returns one. A function factory can capture a setting in a closure and reuse it for every call.

javascript
const multiplyBy = factor => value => value * factor;
const triple = multiplyBy(3);

console.log(triple(5)); // 15
console.log([2, 4].map(triple)); // [6, 12]

The first call binds the factor. The returned function remembers it. The array method receives that function and calls it for each element.

Select with filter

Use filter when you want to keep only elements that satisfy a predicate. JavaScript keeps an element when the callback returns a truthy value.

javascript
const scores = [42, 75, 60];
const passing = scores.filter(score => score >= 60);
console.log(passing); // [75, 60]

The predicate rejects 42. The new array keeps 75 and 60 in their original order.

Transform with map

Use map to compute a new value for each element. The callback’s return value becomes the corresponding result.

javascript
const minutes = [2, 5, 10];
const seconds = minutes.map(value => value * 60);
console.log(seconds); // [120, 300, 600]

The result preserves the order and length of this array. If an arrow callback uses braces, write an explicit return to supply each mapped value.

Combine with reduce

Use reduce to combine elements into a running result. Each callback receives the accumulator and the current element. Its return value becomes the next accumulator.

javascript
const sum = amounts => amounts.reduce((total, amount) => total + amount, 0);
console.log(sum([4, 7, 2])); // 13
console.log(sum([])); // 0

The initial zero makes the totals progress through 4, 11, and 13. An empty array returns the initial value without calling the callback.

Combine collection operations

Use a chain when each stage answers a different question. Here the goal is to sum the value of paid orders. Store prices in cents so this example uses integer arithmetic.

javascript
const orders = [
  { paid: true, quantity: 2, unitCents: 500 },
  { paid: false, quantity: 1, unitCents: 900 },
  { paid: true, quantity: 3, unitCents: 250 },
];

const totalCents = orders
  .filter(order => order.paid)
  .map(order => order.quantity * order.unitCents)
  .reduce((total, amount) => total + amount, 0);

console.log(totalCents); // 1750

Filter keeps the first and third orders. Map produces amounts of 1000 and 750 cents. Reduce adds those amounts, starting at zero.

Compose functions

Composition feeds one function’s result into the next. Use pipe to list single-argument functions in execution order. Compose lists them in reverse, matching nested calls.

javascript
const pipe = (...functions) => input =>
  functions.reduce((value, fn) => fn(value), input);
const compose = (...functions) => input =>
  functions.reduceRight((value, fn) => fn(value), input);

const double = value => value * 2;
const increment = value => value + 1;
const stringify = value => value.toString();

console.log(pipe(double, increment, stringify)(5) === '11'); // true
console.log(compose(stringify, increment, double)(5) === '11'); // true
console.log(pipe(increment, double)(5)); // 12

Both first examples take 5 through 10 and 11 before converting it to text. Incrementing before doubling gives 12, so order matters.

Curry a function

Currying expresses a multi-argument operation as a sequence of single-argument calls. The helper below also accepts groups of arguments and waits until the declared arity is reached.

javascript
const addThree = a => b => c => a + b + c;
console.log(addThree(1)(2)(3)); // 6

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn(...args);
    return (...more) => curried(...args, ...more);
  };
}

const add = curry((a, b, c) => a + b + c);
console.log(add(1)(2)(3), add(1, 2)(3)); // 6 6

Each incomplete call closes over the arguments collected so far. This helper suits fixed-arity functions with ordinary parameters. Function length stops counting at the first default parameter and excludes rest parameters.

Pre-fill arguments

Partial application fixes some arguments now and returns a function that takes the remaining arguments together. Use it to specialize a general operation for a recurring case.

javascript
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const add = (a, b) => a + b;
const addTen = partial(add, 10);
console.log(addTen(5)); // 15

const format = (currency, amount, item) => currency + amount + ' for ' + item;
const inEuros = partial(format, '€');
console.log(inEuros(12, 'lunch')); // €12 for lunch

The returned function places the preset arguments before the new ones. Here the caller supplies both remaining formatting arguments in one call.

Map over an optional value

A Maybe wrapper gives an optional value a map operation. A present value flows through the callbacks. A null or undefined value skips them and can produce a fallback at the end.

javascript
const Maybe = value => ({
  map: fn => value == null ? Maybe(null) : Maybe(fn(value)),
  getOrElse: fallback => value ?? fallback,
});

const double = value => value * 2;
const triple = value => value * 3;
console.log(Maybe(5).map(double).map(triple).getOrElse(0)); // 30
console.log(Maybe(null).map(double).getOrElse(0)); // 0
console.log(Maybe(0).map(double).getOrElse(99)); // 0

Each map returns a new wrapper, so the next map can use the same interface. The nullish checks preserve zero as a present value.

Transform in one pass with transducers

A transducer wraps a reducer’s step function. Use one when you need to reuse transformations with different accumulators or combine filtering and mapping without intermediate arrays.

javascript
const compose = (...functions) => input =>
  functions.reduceRight((value, fn) => fn(value), input);
const transduce = (transform, step, initial, values) =>
  values.reduce(transform(step), initial);

const mapStep = fn => step => (acc, value) => step(acc, fn(value));
const filterStep = test => step => (acc, value) =>
  test(value) ? step(acc, value) : acc;

const transform = compose(
  filterStep(value => value % 2 === 0),
  mapStep(value => value * 3),
);
const append = (acc, value) => {
  acc.push(value);
  return acc;
};
const add = (acc, value) => acc + value;
const values = [1, 2, 3, 4, 5, 6];

console.log(transduce(transform, append, [], values)); // [6, 12, 18]
console.log(transduce(transform, add, 0, values)); // 36

Compose wraps the final step with mapping first and filtering second. At runtime the outer filter sees each input first. It skips 1 and sends 2 to the mapper, which passes 6 to the final step. The array accumulator is created for this run, so appending leaves the input array untouched.

Streams API

The Streams API lets you process data incrementally — read, transform, and write in chunks — without loading the entire payload into memory. ReadableStream, WritableStream, and TransformStream compose via pipeThrough and pipeTo. The Fetch API exposes response bodies as ReadableStream.

A reader receives chunks until the done flag indicates completion. A chunk need not contain a full record or a complete encoded character. Keep decoder state when text spans chunks.

Produce, transform and consume chunks

javascript
// Streams API — process data incrementally without buffering everything

// ReadableStream — produce data chunk by chunk
const createReadable = () => new ReadableStream({
  start(controller) {
    controller.enqueue('Hello ');
    controller.enqueue('world');
    controller.close();
  },
});

// Consume a ReadableStream with a reader
const reader = createReadable().getReader();
const chunks = [];
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  chunks.push(value);
}
console.log(chunks.join(''));   // 'Hello world'
reader.releaseLock();

// WritableStream — accept data chunk by chunk
const writable = new WritableStream({
  write(chunk) { console.log('received:', chunk); },
  close()      { console.log('stream closed'); },
  abort(err)   { console.error('aborted:', err); },
});

// TransformStream — read one side, write the other (pipeable middleware)
const uppercase = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk.toUpperCase());
  },
});

// Pipe chain: readable -> transform -> writable
await createReadable()
  .pipeThrough(uppercase)
  .pipeTo(writable);

A reader consumes chunks one at a time. A pipe instead connects a fresh readable source to a transform and a destination.

Read a download incrementally

javascript
// Fetch body is a ReadableStream — stream a large download
const response = await fetch('/large-file.bin');
const streamReader = response.body.getReader();
let received = 0;
while (true) {
  const { value, done } = await streamReader.read();
  if (done) break;
  received += value.byteLength;
  console.log(`Received ${received} bytes`);
}

// TextDecoderStream / TextEncoderStream — convert bytes to text in a pipe
const textResponse = await fetch('/large-file.txt');
const textStream = textResponse.body
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(new TransformStream({
    transform(chunk, ctrl) { ctrl.enqueue(chunk.toUpperCase()); },
  }));

A fetch body provides byte chunks. Choose a reader or a decoding pipeline before consuming the body.

Fetch & Request/Response

The Fetch API replaces XMLHttpRequest with a Promise-based, stream-aware interface. Request and Response are first-class objects, enabling middleware-style patterns. AbortController provides cancellation, and the body is a ReadableStream you can consume once.

Fetch can fulfill with an HTTP error response. Check response.ok before treating the body as successful data. Reading a body consumes it, so choose one parsing method or clone the response before reading it twice.

Send HTTP requests

javascript
// Basic GET
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
const users = await res.json();

// POST with JSON body
const created = await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice', role: 'admin' }),
});

// Request object — reusable, inspectable
const req = new Request('/api/data', {
  method: 'PUT',
  headers: new Headers({
    'Authorization': 'Bearer token123',
    'Accept': 'application/json',
  }),
  body: JSON.stringify({ value: 42 }),
  cache: 'no-store',
  credentials: 'include',
});
const r2 = await fetch(req);

Check the status before parsing JSON. Set the content type and serialize the payload for a JSON POST.

Consume, cancel and retry requests

javascript
// Clone before consuming (each body can only be read once)
const res = await fetch('/api/users');
if (!res.ok) throw new Error('HTTP ' + res.status);
const clone = res.clone();
const users = await res.json();
const text = await clone.text();

// Alternative readers for other response formats:
// await res.blob();        // binary blob
// await res.arrayBuffer(); // raw bytes
// await res.formData();    // form data

// AbortController — cancel in-flight requests
const ac = new AbortController();
setTimeout(() => ac.abort(), 5000);   // timeout after 5 s
try {
  const data = await fetch('/slow-api', { signal: ac.signal });
} catch (err) {
  if (err.name === 'AbortError') console.log('Request cancelled');
  else throw err;
}

// Retry helper
async function fetchWithRetry(url, opts = {}, retries = 3) {
  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      const res = await fetch(url, opts);
      if (res.ok || attempt === retries) return res;
    } catch (err) {
      if (attempt === retries) throw err;
      await new Promise(r => setTimeout(r, 2 ** attempt * 100));
    }
  }
}

Clone a response before reading it twice. Pass a signal to cancel a fetch, and only retry operations that are safe to repeat.

Web Components

Web Components are a suite of browser standards — Custom Elements, Shadow DOM, and HTML Templates — that let you define reusable, encapsulated HTML elements with their own styles and behaviour, without any framework dependency.

Registration associates a custom tag with the class. The browser calls lifecycle callbacks as the element enters or leaves the document. Release subscriptions on disconnect when the element owns them.

Register an autonomous element

javascript
// Custom Element — autonomous
class MyCard extends HTMLElement {
  static observedAttributes = ['title', 'open'];

  constructor() {
    super();
    // Shadow DOM — encapsulated subtree
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback(name, oldVal, newVal) {
    if (oldVal !== newVal) this.render();
  }

  render() {
    const title = this.getAttribute('title') ?? 'Untitled';
    const open  = this.hasAttribute('open');
    this.shadowRoot.innerHTML = `
      <style>
        :host { display: block; border: 1px solid #ccc; border-radius: 4px; }
        header { padding: 8px 12px; background: #f5f5f5; font-weight: bold; }
        section { display: ${open ? 'block' : 'none'}; padding: 12px; }
      </style>
      <header>${title}</header>
      <section><slot></slot></section>
    `;
    this.shadowRoot.querySelector('header')
      .addEventListener('click', () => this.toggleAttribute('open'));
  }
}
customElements.define('my-card', MyCard);

Register the class before using its tag. Its lifecycle callbacks connect attributes and DOM state to the rendered output.

Extend a built-in and clone a template

javascript
// Customized built-in element (extends existing element)
class FancyButton extends HTMLButtonElement {
  connectedCallback() {
    this.style.borderRadius = '4px';
  }
}
customElements.define('fancy-button', FancyButton, { extends: 'button' });

// HTML Templates — inert, cloneable markup
const template = document.createElement('template');
template.innerHTML = `
  <style>span { color: salmon; }</style>
  <span><slot name='label'>default</slot></span>
`;
class TagBadge extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' })
      .appendChild(template.content.cloneNode(true));
  }
}
customElements.define('tag-badge', TagBadge);

// Usage in HTML:
// <my-card title='Hello' open>
//   <p>Card body goes here</p>
// </my-card>
// <tag-badge><span slot='label'>ES2024</span></tag-badge>

A customized built-in extends an existing HTML element. A template stays inert until its content is cloned and inserted.

Typed Arrays & Buffers

Typed arrays give direct access to raw binary memory via an ArrayBuffer. Fixed-size element views (Int32Array, Float64Array, etc.) and the flexible DataView enable high-performance binary data handling for audio, images, WebGL, networking, and file I/O.

An ArrayBuffer stores bytes and a typed array interprets those bytes as elements. Two views can share storage, so a write through one may change what the other reads. DataView lets the caller choose byte order.

Interpret raw bytes through views

javascript
// Typed arrays wrap an ArrayBuffer — raw binary memory
const buffer = new ArrayBuffer(16);   // 16 bytes
const view   = new DataView(buffer);

// DataView — read/write any type at any byte offset (endian-aware)
view.setInt32(0, 0xDEADBEEF, false);   // big-endian
view.getInt32(0, false);               // -559038737 (0xDEADBEEF signed)
view.setFloat64(8, Math.PI, true);     // little-endian
view.getFloat64(8, true);              // 3.141592653589793

// Typed array views — each element is a fixed type
const i32 = new Int32Array(buffer);    // 4 elements (4 bytes each)
const f32 = new Float32Array(4);       // allocates own 16-byte buffer
const u8  = new Uint8Array(buffer);    // 16 elements (1 byte each)

// Shared underlying buffer
const original = new Int16Array([1, 2, 3, 4]);
const alias    = new Uint8Array(original.buffer);   // same memory

// Creating typed arrays
const a = new Float32Array([1.5, 2.5, 3.5]);
const b = Float32Array.from([1, 2, 3], x => x * 0.5);
const c = new Int32Array(8);          // zeroed, length 8
const d = new Uint8Array(a.buffer, 4, 4);  // offset 4, 4 bytes

DataView reads and writes at byte offsets. Typed arrays give fixed-type access, and two views of the same buffer see the same bytes.

Process typed values and encode text

javascript
// Typed array API (mostly mirrors Array)
a.length;          // 3
a.byteLength;      // 12
a.byteOffset;      // 0
a.buffer;          // underlying ArrayBuffer
a.set([10, 20]);   // overwrite from index 0
a.subarray(1, 3);  // view without copy
a.slice(0, 2);     // new typed array with copy
a.sort();          // in-place numeric sort
a.fill(0);         // zero out

// Blob / File to ArrayBuffer
async function fileToBuffer(file) {
  return file.arrayBuffer();
}

// TextEncoder / TextDecoder
const enc = new TextEncoder();
const bytes = enc.encode('Hello');       // Uint8Array
const dec = new TextDecoder('utf-8');
dec.decode(bytes);                       // 'Hello'

Typed array methods operate on numeric elements. TextEncoder and TextDecoder convert between strings and UTF-8 bytes.

Web Storage & IndexedDB

localStorage and sessionStorage offer synchronous string key-value storage capped at ~5 MB. IndexedDB is the browser's full async object database: it supports structured data, indexes, cursors, and multi-object-store transactions with significantly higher storage limits.

Web Storage stores strings, so structured values need encoding and decoding. IndexedDB operations use asynchronous requests in transactions. Wait for transaction completion when the next step depends on a committed write.

Persist strings in web storage

javascript
// localStorage / sessionStorage — synchronous, string key-value
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');   // 'dark'
localStorage.removeItem('theme');
localStorage.clear();

// Store objects by JSON-serialising
localStorage.setItem('user', JSON.stringify({ id: 1, name: 'Alice' }));
const user = JSON.parse(localStorage.getItem('user'));

// sessionStorage — same API, cleared when tab closes
sessionStorage.setItem('draft', 'unsaved content');

// Storage event — fired in OTHER tabs/windows on same origin
window.addEventListener('storage', (e) => {
  console.log(e.key, e.oldValue, e.newValue, e.storageArea);
});

Serialize objects to JSON for string storage. Session storage is scoped to a tab, and the storage event reports changes from another eligible document.

Store structured data in IndexedDB

javascript
// ── IndexedDB — async, structured, supports indexes & transactions ──────────
const request = indexedDB.open('myDB', 1);

request.onupgradeneeded = (e) => {
  const db = e.target.result;
  const store = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
  store.createIndex('by_name', 'name', { unique: false });
};

request.onsuccess = (e) => {
  const db = e.target.result;

  // Write
  const tx = db.transaction('users', 'readwrite');
  tx.objectStore('users').add({ name: 'Alice', age: 30 });
  tx.commit();

  // Read by key
  const tx2  = db.transaction('users', 'readonly');
  const get  = tx2.objectStore('users').get(1);
  get.onsuccess = () => console.log(get.result);

  // Cursor over index
  const tx3  = db.transaction('users', 'readonly');
  const idx  = tx3.objectStore('users').index('by_name');
  idx.openCursor().onsuccess = function() {
    const cursor = this.result;
    if (!cursor) return;
    console.log(cursor.value);
    cursor.continue();
  };
};

// Promise wrapper for concise async usage
function idbGet(db, storeName, key) {
  return new Promise((resolve, reject) => {
    const req = db.transaction(storeName).objectStore(storeName).get(key);
    req.onsuccess = () => resolve(req.result);
    req.onerror   = () => reject(req.error);
  });
}

Create the store during a version upgrade and use transactions for reads and writes. The wrapper adapts a request to a promise.

Dynamic Import & Code Splitting

The import() expression loads an ES module on demand and returns a Promise. Bundlers (Vite, webpack, Rollup) use dynamic imports as split points to emit separate chunks, so users only download the code they actually need. import.meta exposes module-level metadata including the module's URL.

Calling import as an expression starts loading the module and returns a promise for its namespace. Await it where the feature needs the module and handle load failures there.

Load modules when needed

javascript
// Static import — resolved at parse time, always hoisted
import { format } from './date-utils.js';

// Dynamic import() — returns a Promise, evaluated at runtime
const { format } = await import('./date-utils.js');

// Conditional loading — only pay for what you use
async function loadChart(type) {
  if (type === 'bar') {
    const { BarChart } = await import('./charts/bar.js');
    return new BarChart();
  }
  const { LineChart } = await import('./charts/line.js');
  return new LineChart();
}

// Route-based code splitting (e.g. with a router)
const routes = {
  '/':        () => import('./pages/Home.js'),
  '/about':   () => import('./pages/About.js'),
  '/contact': () => import('./pages/Contact.js'),
};

async function navigate(path) {
  const load = routes[path] ?? routes['/'];
  const { default: Page } = await load();
  document.getElementById('app').replaceChildren(new Page().render());
}

Keep static imports for eager dependencies and use dynamic imports for optional features or routes.

Prepare assets and handle loading failures

javascript
// Prefetch — hint the browser to load a module before it's needed
function prefetch(specifier) {
  const link = document.createElement('link');
  link.rel  = 'modulepreload';
  link.href = specifier;
  document.head.appendChild(link);
}
prefetch('./pages/About.js');   // load now, use later

// import.meta — module metadata
console.log(import.meta.url);         // absolute URL of the current module
const assetUrl = new URL('./logo.svg', import.meta.url).href;

// Top-level await — module execution pauses until resolved
// (works at the top level of an ES module, not inside functions)
const config = await fetch('/api/config').then(r => r.json());
export const API_BASE = config.apiBase;

// Dynamic import with error handling
async function safeDynImport(specifier) {
  try {
    return await import(specifier);
  } catch (err) {
    console.error('Failed to load module:', specifier, err);
    return null;
  }
}

Resolve an asset relative to the current module with import.meta.url. Top-level await delays dependent evaluation, and a rejected import can be caught.

Observable Patterns

Observables model lazy, push-based event streams — they do nothing until subscribed and can be composed with operators (map, filter, merge). A Subject is both an Observable and an Observer, enabling multicast. This pattern underpins RxJS and the TC39 Observable proposal.

A subscription gives the producer a consumer for pushed values. Its cleanup should stop work and release resources when the subscriber is finished.

Build a lazy observable

javascript
// Observable pattern — push-based event stream with lazy evaluation

// 1. Minimal Observable implementation
class Observable {
  constructor(subscribe) { this._subscribe = subscribe; }

  subscribe(observer) {
    const obs = typeof observer === 'function'
      ? { next: observer, error: console.error, complete: () => {} }
      : observer;
    return this._subscribe(obs);
  }

  // Operators return new Observables (composable pipeline)
  map(fn) {
    return new Observable(obs => {
      return this.subscribe({
        next:     x => obs.next(fn(x)),
        error:    e => obs.error(e),
        complete: () => obs.complete(),
      });
    });
  }

  filter(pred) {
    return new Observable(obs => {
      return this.subscribe({
        next:     x => pred(x) && obs.next(x),
        error:    e => obs.error(e),
        complete: () => obs.complete(),
      });
    });
  }

  static fromEvent(target, event) {
    return new Observable(obs => {
      const handler = e => obs.next(e);
      target.addEventListener(event, handler);
      return () => target.removeEventListener(event, handler);   // unsubscribe
    });
  }

  static interval(ms) {
    return new Observable(obs => {
      let n = 0;
      const id = setInterval(() => obs.next(n++), ms);
      return () => clearInterval(id);
    });
  }
}

Subscription starts the producer. Operators wrap the source so each subscriber receives transformed or filtered events.

Broadcast events and tear down subscriptions

javascript
// 2. Subject — both Observable and Observer (multicast)
class Subject extends Observable {
  #observers = [];
  constructor() {
    super(obs => {
      this.#observers.push(obs);
      return () => { this.#observers = this.#observers.filter(o => o !== obs); };
    });
  }
  next(value)    { this.#observers.forEach(o => o.next(value)); }
  error(err)     { this.#observers.forEach(o => o.error(err)); }
  complete()     { this.#observers.forEach(o => o.complete()); }
}

// Usage
const clicks = Observable.fromEvent(document, 'click');
const unsubscribe = clicks
  .filter(e => e.target.matches('button'))
  .map(e => e.target.textContent)
  .subscribe(text => console.log('button clicked:', text));

// Tear down later
unsubscribe();

Use the Observable class from the previous example. A subject broadcasts to its subscribers, and unsubscribing releases the event listener in the click example.

Best Practices

Modern JS Idioms

Use modern syntax when it clarifies intent. Distinguish missing values from other falsy values when choosing defaults.

Use a fallback that matches the values you consider absent. Nullish coalescing keeps valid falsy values, such as zero, while logical OR replaces them.

Handle bindings and missing values

javascript
// Prefer const over let over var
const MAX = 100;
let count = 0;
// var x = 1;  // avoid — function-scoped, hoisted

// Destructuring
const { name, age = 0 } = user;
const [first, ...rest] = items;

// Optional chaining — no more TypeError on nullish
const city = user?.address?.city;
const first2 = arr?.[0];
const result2 = obj?.method?.();

// Nullish coalescing — only falls back on null/undefined
const port = config.port ?? 3000;
const label = value ?? 'default';

// Logical assignment operators
settings.theme ||= 'light';    // set if falsy
settings.debug &&= isProd;     // clear if truthy
cache.entry ??= computeValue(); // set if nullish

Use destructuring for named inputs and nullish operators when zero or an empty string should remain valid.

Transform collections with explicit operations

javascript
// Array methods — prefer over manual loops
const doubled = nums.map(x => x * 2);
const evens = nums.filter(x => x % 2 === 0);
const sum = nums.reduce((acc, x) => acc + x, 0);
const found = users.find(u => u.id === id);
const allActive = users.every(u => u.active);
const anyAdmin = users.some(u => u.role === 'admin');

// Object.entries / fromEntries for transforms
const upper = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k, v.toUpperCase()])
);

// Spread for shallow copy — never mutate in place
const updated = { ...original, status: 'done' };
const merged = [...arr1, ...arr2];

// Promise combinators
await Promise.all([fetchA(), fetchB()]);           // all must resolve
await Promise.allSettled([fetchA(), fetchB()]);    // partial failures OK
await Promise.race([fetchA(), timeout(5000)]);     // first to settle
await Promise.any([mirror1(), mirror2()]);         // first to resolve

// globalThis — works in browser, Node, workers
globalThis.setTimeout(() => {}, 0);

Choose the array method by the result you need. Spread makes a shallow copy, and promise combinators express how asynchronous results are combined.

Functions & Scope

Keep functions focused and dependencies visible through parameters. Closures provide private state but retained references can also extend object lifetimes.

Keep dependencies visible as parameters when callers need to substitute them. A function that computes from its arguments can be tested with ordinary inputs and expected results.

Make function inputs explicit

javascript
// Prefer pure functions — no side effects, deterministic output
const add = (a, b) => a + b;                 // pure
// let total = 0; function addSide(x) { total += x; }  // impure

// Arrow functions for callbacks — shorter, no own `this`
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);

// Avoid `this` in regular functions when using as callbacks
// element.addEventListener('click', function() { this... }); // fragile
element.addEventListener('click', () => doWork());           // safer

// Default parameters — document intent, avoid || hacks
function greet(name, greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}

// Rest params over the `arguments` object
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
// function oldSum() { [].reduce.call(arguments, ...) }  // avoid

Use defaults for omitted arguments and rest for variable-length input. A pure function derives its result from its inputs.

Scope private state and name functions

javascript
// Closure for private state
function makeCounter(start = 0) {
  let count = start;
  return {
    increment: () => ++count,
    value: () => count,
  };
}

// Memoize expensive computations
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}
const fib = memoize(n => (n <= 1 ? n : fib(n - 1) + fib(n - 2)));

// Avoid function hoisting surprises — use const for function expressions
const process = (x) => x * 2;  // not callable before this line
// function process(x) { ... }  // hoisted — callable anywhere in scope

// Named functions for readable stack traces
const handleClick = function handleClick(e) { e.preventDefault(); };

A closure can own a cache or private counter. A named function gives readers and stack traces a stable identifier.

Async Patterns

Handle failures and choose deliberate sequencing or concurrency. Abandoning a promise does not stop its work; cancellation requires support from the operation.

Await dependent operations in sequence. Use Promise.all for independent results needed together and handle its rejection where the overall operation can recover.

Handle asynchronous failures

javascript
// Always await or .catch() — never ignore Promise rejections
const data = await fetchData();                     // await
fetchData().then(use).catch(handleError);           // chain

// Prefer async/await over raw .then() chains
async function loadUser(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// Handle errors at every async boundary
async function renderProfile(id) {
  try {
    const user = await loadUser(id);
    render(user);
  } catch (err) {
    showError(err.message);
  }
}

Await or attach a rejection handler at the call site. Catch an error where the caller can recover or add context.

Cancel work and keep partial results

javascript
// AbortController for cancellable fetch
function fetchWithTimeout(url, ms = 5000) {
  const ac = new AbortController();
  const timer = setTimeout(() => ac.abort(), ms);
  return fetch(url, { signal: ac.signal })
    .finally(() => clearTimeout(timer));
}

// Promise.allSettled when partial failures are OK
const results = await Promise.allSettled([fetchA(), fetchB(), fetchC()]);
const successes = results
  .filter(r => r.status === 'fulfilled')
  .map(r => r.value);

// Avoid mixing callbacks and Promises
// Bad: new Promise(resolve => fs.readFile(path, (err, d) => resolve(d)))
// Good: use fs.promises.readFile(path) directly

// queueMicrotask for scheduling — runs before next macrotask
queueMicrotask(() => {
  // Runs after current sync code, before setTimeout
  notifySubscribers();
});

// Global unhandled rejection safety net
window.addEventListener('unhandledrejection', (e) => {
  console.error('Unhandled rejection:', e.reason);
});

An abort signal cancels a fetch. Promise.allSettled lets successful operations remain useful when another operation fails.

Objects & Immutability

Treat shared mutation as an explicit design choice. Copy the levels being changed because spread does not recursively isolate nested state.

Freeze applies to the object’s own properties. Nested objects still need their own treatment. When updating nested state with spread, copy each level along the changed path.

Copy or freeze data deliberately

javascript
// Object.freeze for true constants
const CONFIG = Object.freeze({
  API_BASE: 'https://api.example.com',
  TIMEOUT: 5000,
});
// CONFIG.TIMEOUT = 9999;  // silently ignored (throws in strict mode)

// structuredClone for deep copy — handles Date, Map, Set, undefined
const clone = structuredClone(original);
// JSON round-trip loses Dates, Maps, Sets, undefined — avoid for those

// Never mutate function arguments
function normalize(user) {
  return { ...user, name: user.name.trim() };   // new object
  // user.name = user.name.trim();               // mutates caller's object!
}

Freeze protects the top level, structuredClone copies supported nested values, and an update can return a new object.

Choose safe key storage

javascript
// Map over plain object for dynamic keys
const counts = new Map();
counts.set('alice', 1);
counts.set('bob', 2);
counts.get('alice');            // 1 — no prototype collision risk
// { alice: 1 }['constructor'] // inherited — avoid for untrusted keys

// Set for unique values
const unique = [...new Set(duplicates)];
const tags = new Set(['js', 'ts', 'js']);   // Set { 'js', 'ts' }

// Avoid prototype pollution
// obj.__proto__ = evil;              // never
// Object.assign(target, untrusted); // risk if untrusted has __proto__
const safe = Object.assign(Object.create(null), untrusted); // safe merge

// Object.hasOwn over hasOwnProperty (works on null-proto objects)
if (Object.hasOwn(obj, 'key')) { /* ... */ }
// obj.hasOwnProperty('key')  // fails on Object.create(null) objects

// WeakMap for private instance data
const _state = new WeakMap();
class Store {
  constructor(init) { _state.set(this, { ...init }); }
  get(key) { return _state.get(this)[key]; }
}

Map and Set handle dynamic keys and uniqueness. Use own-property checks for dictionaries and WeakMap for object-associated private state.

Error Handling

Include enough operation context to diagnose failures. Recover only when a valid fallback exists instead of hiding programming errors.

Throw Error objects so callers get a message and stack. When a layer translates a failure into a domain error, keep its cause so debugging retains the original context.

Throw meaningful errors

javascript
// Always throw Error objects — not strings
throw new Error('Something went wrong');
// throw 'oops';  // no stack trace, instanceof checks fail

// Add meaningful messages
throw new Error(`User ${id} not found in region ${region}`);

// Custom error subclasses for structured handling
class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'AppError';
    this.code = code;
  }
}
class NetworkError extends AppError {
  constructor(message, status) {
    super(message, 'NETWORK_ERROR');
    this.name = 'NetworkError';
    this.statusCode = status;
  }
}

An Error carries a message and stack. A custom subtype gives callers a way to distinguish a specific failure category.

Recover or report at a boundary

javascript
// Never swallow errors silently
try {
  riskyOp();
} catch (err) {
  // console.log(err);  // don't silently swallow
  logger.error('riskyOp failed', { err });
  throw err;             // re-throw if caller needs to know
}

// Global safety nets
window.addEventListener('error', (e) => {
  logger.error('Uncaught error', { message: e.message, filename: e.filename });
});
window.addEventListener('unhandledrejection', (e) => {
  logger.error('Unhandled rejection', { reason: e.reason });
  e.preventDefault();
});

// try/catch in every async function
async function save(data) {
  try {
    await db.write(data);
  } catch (err) {
    throw new AppError(`Save failed: ${err.message}`, 'DB_WRITE_ERROR');
  }
}

// Error boundaries in UI — wrap risky render paths
function safeRender(component, fallback) {
  try {
    return component.render();
  } catch (err) {
    console.error('Render error:', err);
    return fallback;
  }
}

Log, recover or propagate according to what the caller can do. Global handlers and UI fallbacks catch failures at broader boundaries.

Performance

Profile representative workloads and watch long synchronous tasks. Batch related updates and avoid repeated expensive computation before adding complex optimizations.

Profile the interaction before choosing an optimization. If repeated layout dominates, batch DOM changes. If work runs too often, reduce how often it runs and measure again.

Limit layout and event work

javascript
// Avoid layout thrashing — batch DOM reads before writes
// Bad: read offsetLeft, write style.left, read, write... (forces reflow each time)
const positions = elements.map(el => el.offsetLeft);   // read phase
elements.forEach((el, i) => {                          // write phase
  el.style.left = (positions[i] + 1) + 'px';
});

// Debounce high-frequency handlers (resize, scroll, input)
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
window.addEventListener('resize', debounce(recalcLayout, 150));

// Throttle for rate-limited handlers (scroll position, mouse move)
function throttle(fn, ms) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= ms) { last = now; fn(...args); }
  };
}

// requestAnimationFrame for smooth animations
function animate(timestamp) {
  el.style.transform = `translateX(${(timestamp * 0.05) % 400}px)`;
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

// Prefer CSS transitions over JS animations when possible
// el.style.transition = 'transform 0.3s ease';  then toggle a class

Batch measurements and updates. Debounce waits for a quiet period, while throttling limits how often a handler runs.

Reduce DOM and main-thread work

javascript
// Cache DOM queries — querySelector is not free
const list = document.getElementById('list');    // once
items.forEach(item => list.appendChild(buildRow(item)));

// DocumentFragment for bulk DOM insertions — single reflow
const frag = document.createDocumentFragment();
for (const item of items) {
  const li = document.createElement('li');
  li.textContent = item.label;
  frag.appendChild(li);
}
list.appendChild(frag);

// Virtualize long lists — render only visible rows (e.g. virtual-scroller)

// Remove event listeners to prevent memory leaks
const handler = () => doWork();
el.addEventListener('click', handler);
// later:
el.removeEventListener('click', handler);

// Web Workers for CPU-intensive work — keeps main thread responsive
const worker = new Worker('./heavy.js');
worker.postMessage({ data: largeArray });
worker.onmessage = (e) => renderResult(e.data);

Reuse queried nodes, batch inserts and render only visible rows when appropriate. Remove unused listeners and move expensive computation to a worker.

Diagram
100%