FE·15
JavaScript
The language and its runtime: values and types, scope and closures, prototypes and classes, asynchronous programming, the event loop in detail, and the advanced built-ins, each compared with Java, Go, Rust and C++ where the contrast teaches something.
Start here: programming in JavaScript
What JavaScript is
JavaScript is the programming language built into every browser. It was designed in 1995 to make pages interactive, and it now runs everywhere: in browsers, on servers (Node.js, Deno, Bun), in desktop and mobile apps. The language itself is standardised as ECMAScript (one edition a year: ES2015 brought most of the modern syntax you'll see here). It's dynamically typed (variables don't declare a type; values carry them), garbage-collected (memory is freed for you), and single-threaded with an event loop (one piece of your code runs at a time, and waiting for things like network replies happens in the background). Each of those three properties gets a full section later in the chapter.
Values and types
Every value has a type. typeof tells you which:
console.log(typeof 42, typeof 3.5, typeof "dosa", typeof true, typeof undefined,
typeof null, typeof {}, typeof [], typeof (() => 1), typeof 10n);
number number string boolean undefined object object object function bigint
- number: one type for integers and decimals (a 64-bit floating-point number, Volume 1 chapter 6). bigint (
10n) holds integers of any size. - string: text, in
"double",'single'or`backtick`quotes. - boolean:
trueorfalse. - undefined: "no value was given" (a variable you never assigned, a missing property). null: "deliberately empty".
typeof nullsaying"object"is a famous 1995 bug that can never be fixed without breaking the web. - object: everything else: plain objects
{}, arrays[], functions, dates. These are the building blocks you'll use most.
Arithmetic mostly works as you'd expect, with the floating-point quirks from Volume 1:
0.1 + 0.2 → 0.30000000000000004
7 / 2 → 3.5 (no integer division; use Math.floor(7 / 2) → 3)
7 % 2 → 1 (remainder)
2 ** 10 → 1024
10 / 0 → Infinity
"abc" * 2 → NaN ("not a number": the result of failed arithmetic)
Variables: const and let
const dish = "Masala dosa"; // const: this name will always refer to this value
let cups = 0; // let: this name can be reassigned
cups = cups + 1;
Use const by default and let only when you need to reassign. const stops reassignment, not change: a const array can still grow.
const order = ["idli"];
order.push("vada"); // fine: the array changes, the name still refers to the same array
console.log(order); // [ 'idli', 'vada' ]
const x = 1; x = 2; // TypeError: Assignment to constant variable.
You'll see the older var in old code; avoid it (its scoping rules are surprising, as the full-depth section shows).
Strings and template literals
const dish = "Masala dosa", price = 90;
console.log(`${dish} costs ₹${price}; with GST ₹${(price * 1.05).toFixed(2)}`);
console.log(dish.length, dish.toUpperCase(), dish.includes("dosa"), dish.split(" "));
Masala dosa costs ₹90; with GST ₹94.50
11 MASALA DOSA true [ 'Masala', 'dosa' ]
Backtick strings (template literals) can contain ${expressions} and span several lines. Strings are immutable: toUpperCase() returns a new string.
Comparison: always use ===
JavaScript has two equality operators. == converts types before comparing, with rules few people remember; === ("strict equality") doesn't:
5 == "5" → true 5 === "5" → false
null == undefined → true null === undefined → false
0 == "" → true 0 === "" → false
NaN === NaN → false Number.isNaN(NaN) → true
The same automatic conversion (coercion) affects +, which joins strings if either side is a string:
"5" + 3 → "53" "5" - 3 → 2 "5" * "2" → 10 true + 1 → 2
Rules for staying sane: use === and !== always; convert explicitly with Number(text) and String(n); and remember that numbers typed into form fields arrive as strings ("5" + 3 is how a shopping cart shows ₹53 instead of ₹8).
Truthy and falsy
Conditions accept any value. Exactly these are falsy (treated as false): false, 0, "", null, undefined, NaN (plus 0n). Everything else is truthy, including "0", [] and {}:
[0, "", null, undefined, NaN, "0", [], {}].map(Boolean)
→ false false false false false true true true
Two operators build on this. a || b gives b when a is falsy; a ?? b gives b only when a is null or undefined. The difference matters for real zeros:
null ?? "default" → "default" 0 ?? "default" → 0 0 || "default" → "default"
And ?. (optional chaining) stops at a missing value instead of throwing: menu[5]?.name is undefined rather than the Start Here chapter's "Cannot read properties of undefined".
Control flow
if (cups === 0) {
console.log("No chai yet");
} else if (cups < 3) {
console.log("Reasonable");
} else {
console.log("Maybe switch to water");
}
for (let i = 1; i <= 3; i++) console.log(`Cup ${i}`); // counting loop
for (const item of ["dosa", "idli"]) console.log(item); // loop over the values of an array (or string, map, set)
while (queue.length > 0) handle(queue.shift()); // loop while a condition holds
for…of loops over values. There's also for…in, which loops over an object's property names; it's rarely what you want for arrays.
Functions
function addTax(amount, rate = 0.05) { // a function declaration, with a default parameter
return amount * (1 + rate);
}
const half = n => n / 2; // an arrow function: shorter, common for small callbacks
console.log(addTax(100), addTax(100, 0.18), half(90)); // 105 118 45
Functions are values: you can store them in variables, put them in arrays, pass them to other functions and return them. Passing a function to another function (a callback) is everywhere in JavaScript: addEventListener("click", fn), setTimeout(fn, 1000), array.map(fn).
A function can also remember the variables around it when it was created. That's a closure:
function makeCounter() {
let count = 0;
return () => ++count; // this arrow function keeps access to count
}
const next = makeCounter();
next(); next();
console.log(next()); // 3
Nothing outside can touch count except through next. Closures are how event handlers remember their state, and how modules and React hooks keep private data.
Arrays and objects: modelling data
An array is an ordered list; an object is a set of named properties. Real data is usually arrays of objects:
const menu = [
{ name: "Masala dosa", price: 90, veg: true },
{ name: "Chicken 65", price: 180, veg: false },
{ name: "Idli (2)", price: 50, veg: true },
];
console.log(menu[0].name, menu.length); // Masala dosa 3
Arrays come with methods that take a callback and replace most hand-written loops:
menu.filter(d => d.veg).map(d => d.name) // [ 'Masala dosa', 'Idli (2)' ] keep some, transform each
menu.reduce((sum, d) => sum + d.price, 0) // 320 combine into one value
menu.find(d => d.price > 100)?.name // 'Chicken 65' first match
menu.some(d => !d.veg) // true any match?
[...menu].sort((a, b) => a.price - b.price) // cheapest first (copy first: sort changes the array)
One trap worth memorising now: sort() without a comparison function sorts as strings:
[10, 9, 1, 100].sort() → [ 1, 10, 100, 9 ]
[10, 9, 1, 100].sort((a, b) => a - b) → [ 1, 9, 10, 100 ]
Destructuring pulls values out by name or position, and spread (...) copies or combines:
const { name, price, ...rest } = menu[0]; // name = 'Masala dosa', price = 90, rest = { veg: true }
const cheaper = { ...menu[0], price: 80 }; // a copy with one property changed
JSON is these structures as text: JSON.stringify(menu[2]) gives {"name":"Idli (2)","price":50,"veg":true}, and JSON.parse turns text back into objects.
Errors
When something goes wrong, JavaScript throws an error object, which travels up through the calling functions until something catches it, or it reaches the top and appears in the Console as "Uncaught …":
function parsePrice(text) {
const n = Number(text);
if (Number.isNaN(n)) throw new Error(`not a price: "${text}"`);
return n;
}
try {
parsePrice("ninety");
} catch (e) {
console.log("caught:", e.message); // caught: not a price: "ninety"
} finally {
console.log("finally runs either way");
}
Catch errors where you can do something useful about them (show a message, retry, use a default), not everywhere.
Asynchronous code: waiting without freezing
A web page can't stop and wait for a server: while it waits, it must keep responding to clicks and scrolling. So operations that take time (network requests, timers, reading files) are asynchronous: you start them, carry on, and get the result later. Watch the order of this output:
console.log("1. start");
setTimeout(() => console.log("4. timeout callback (0 ms)"), 0);
Promise.resolve().then(() => console.log("3. promise callback"));
console.log("2. end of script");
1. start
2. end of script
3. promise callback
4. timeout callback (0 ms)
Even a 0 ms timer runs after the current code finishes. The event loop runs one piece of code to completion, then picks the next waiting job; promise callbacks go before timers. The full-depth section explains exactly why.
A promise is an object representing a result that isn't ready yet. await (inside an async function, or at the top level of a module) pauses that function until the promise settles, while the rest of the page keeps running. Against a local test server that takes 300 ms per request:
for (const d of ["dosa", "idli", "vada"]) { const r = await fetch(base + d); await r.json(); }
// one after another: 951 ms
const all = await Promise.all(["dosa", "idli", "vada"].map(d => fetch(base + d).then(r => r.json())));
// all at once with Promise.all: 308 ms
Awaiting in a loop runs the requests one after another; starting them all and awaiting Promise.all runs them at the same time. When requests don't depend on each other, start them together.
Two facts about fetch that catch everyone:
fetch to a closed port: TypeError fetch failed | cause: ECONNREFUSED (network failure: the promise rejects)
fetch of a missing page: 404 does not throw: 404 false no such dish (HTTP errors resolve normally; check r.ok)
give up after 100 ms: TimeoutError The operation was aborted due to timeout (fetch(url, { signal: AbortSignal.timeout(100) }))
So the correct shape is:
try {
const r = await fetch(url, { signal: AbortSignal.timeout(5000) });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const data = await r.json();
// use data
} catch (e) {
// network down, timed out, or HTTP error: tell the user
}
Modules
Real programs are split into files. A module exports what it wants to share, and other modules import it:
// prices.js
export const GST = 0.05;
export function withGst(amount) { return Math.round(amount * (1 + GST)); }
export default function formatRupees(n) {
return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(n);
}
// main.js
import formatRupees, { withGst, GST } from "./prices.js";
console.log(`GST ${GST * 100}%:`, formatRupees(withGst(90)), "|", formatRupees(1234567.5));
GST 5%: ₹95.00 | ₹12,34,567.50
In a browser, load the entry file with <script type="module" src="main.js"> (served over HTTP). Intl.NumberFormat knows Indian digit grouping (lakhs and crores) and every other locale's conventions; use it rather than formatting numbers by hand.
How deep to go in JavaScript
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name the types, declarations, operators, array methods and async keywords |
| L2 | Write correct programs with objects, arrays, functions, modules, errors and async/await |
| L3 | Explain coercion, scope and closures, this, prototypes, the event loop (tasks, microtasks, rendering), promises and iterators |
| L4 | Diagnose ordering bugs, race conditions, long tasks, memory leaks and precision errors with DevTools and logs |
| L5 | Design module boundaries, async flows (cancellation, retries, concurrency limits) and data modelling |
| L6 | Run JavaScript at scale: performance budgets, runtime differences (browser, Node, edge), upgrade strategy |
The language
Primitives and the type system
JavaScript is dynamically typed: values have types, variables don't (Vol. 1 ch. 2). There are eight types: seven primitives plus object.
| Type | Examples | Notes |
|---|---|---|
undefined |
undefined |
"No value assigned": missing properties, missing arguments, functions without return |
null |
null |
"Intentionally empty". typeof null === "object" is a historic bug kept for compatibility |
boolean |
true, false |
|
number |
42, 3.14, NaN, Infinity, -0 |
Always an IEEE 754 double (Vol. 1 ch. 6). Integers are exact only up to 2⁵³ − 1 (Number.MAX_SAFE_INTEGER) |
bigint |
9007199254740993n |
Arbitrary-precision integers. Can't mix with number without explicit conversion |
string |
"héllo", `x=${x}` |
Immutable sequences of UTF-16 code units ("😀".length === 2) |
symbol |
Symbol("id"), Symbol.iterator |
Unique identity, used for non-colliding property keys and protocol hooks |
object |
{}, [], functions, Date, Map… |
Everything else. Arrays and functions are objects too |
Primitives are immutable values compared by value. Objects are compared by reference (identity), like Java objects and unlike Go or C structs:
"a" === "a"; // true
[1] === [1]; // false: two different objects
const a = { x: 1 }, b = a;
b.x = 2; // a.x is 2 as well: shared reference
Wrapper objects: "abc".toUpperCase() works because the engine temporarily wraps the primitive in a String object. Never create wrappers yourself (new String("a"), new Boolean(false)): new Boolean(false) is a truthy object.
Coercion is where JavaScript surprises people. == converts types before comparing, while === doesn't:
0 == "0"; // true 0 === "0"; // false
null == undefined; // true (the one commonly accepted == use: x == null checks both)
[] + {}; // "[object Object]" (both converted to strings)
"5" * 2; // 10 ("5" → number)
"5" + 2; // "52" (+ prefers string concatenation)
NaN === NaN; // false → use Number.isNaN(x) or Object.is(x, NaN)
Object.is(0, -0);// false (=== says true)
Truthiness: the falsy values are exactly false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", "false", [] and {}. Use === everywhere (ESLint's eqeqeq rule), and write explicit checks (if (count > 0), if (name !== "")) where 0 or "" are valid values.
Numbers in practice: there's no separate integer type, so 0.1 + 0.2 !== 0.3, as in every IEEE language. Money needs integer minor units (Vol. 1 ch. 6). parseInt("08") is 8, but always pass the radix: parseInt(s, 10). Number("") is 0 and Number("12px") is NaN. Large IDs from a Java or Go backend that exceed 2⁵³ must be sent as strings (Vol. 1 ch. 6), or parsed with BigInt.
Variables: var, let and const
| Scope | Hoisting | Re-assign | Re-declare | |
|---|---|---|---|---|
var |
Function (or global) | Hoisted and initialised to undefined |
Yes | Yes |
let |
Block | Hoisted but in the TDZ until declared | Yes | No |
const |
Block | Hoisted, TDZ | No (the binding; the object can still mutate) | No |
Use const by default, let when you must reassign, and never var. const means the same as Java's final or a Rust let binding without mut for the binding only. const arr = []; arr.push(1) is fine. For deep immutability, use Object.freeze() (shallow), immutable data libraries, or TypeScript's readonly.
Objects and arrays
Objects are dynamic maps from string or symbol keys to values, with prototypes (covered below):
const user = {
name: "Asha",
"favourite-colour": "teal", // any string key works with quotes
[`role_${id}`]: "admin", // computed key
greet() { return `Hi ${this.name}`; }, // method shorthand
};
user.name; user["favourite-colour"];
delete user.name; // removes a property (slow path in engines; avoid in hot code)
"name" in user; // checks the prototype chain too
Object.hasOwn(user, "name"); // own property only
Object.keys(user); Object.entries(user); Object.fromEntries(pairs);
structuredClone(user); // deep copy (fails on functions)
Key order is insertion order for string keys, but integer-like keys come first in ascending order. Use Map when keys are arbitrary or non-string, when you add and remove often, or when you need size and iteration performance. Plain objects are for records with known shapes, and they're also prone to prototype pollution (chapter 28).
Arrays are objects with integer keys and a length. Engines store them as real contiguous arrays when they're dense and homogeneous (packed SMI or packed double elements in V8). Holes ([1, , 3]) and mixed types push them to slower representations.
const xs = [5, 1, 4];
xs.map(x => x * 2); // [10, 2, 8]: new array
xs.filter(x => x > 2); // [5, 4]
xs.reduce((s, x) => s + x, 0); // 10
xs.find(x => x > 3); // 5; findLast, findIndex, some, every, includes, flatMap…
xs.toSorted((a, b) => a - b);// [1, 4, 5]: non-mutating (ES2023): toSorted, toReversed, toSpliced, with(i, v)
xs.sort(); // MUTATES, and compares as STRINGS by default: [10, 9, 1].sort() → [1, 10, 9]
xs.at(-1); // last element
Array.from({ length: 3 }, (_, i) => i * i); // [0, 1, 4]
Object.groupBy(people, p => p.dept); // ES2024 grouping
sort() without a comparator converts elements to strings, so always pass (a, b) => a - b for numbers. Array.prototype.sort is required to be stable since ES2019 (it's TimSort in V8, Vol. 1 ch. 4).
Functions
Functions are first-class objects (Vol. 1 ch. 2): they're stored, passed, returned, and can carry properties. There are several forms:
function add(a, b = 0) { return a + b; } // declaration: hoisted, has its own `this` and `arguments`
const mul = function (a, b) { return a * b; }; // function expression
const sq = (x) => x * x; // arrow: lexical `this`, no `arguments`, can't be `new`ed
const sum = (...nums) => nums.reduce((s, n) => s + n, 0); // rest parameters
async function load() { /* returns a Promise */ }
function* ids() { let i = 0; while (true) yield i++; } // generator
this is decided by how a function is called, not where it's defined (except for arrow functions, which capture this lexically like any other variable):
| Call | this |
|---|---|
obj.method() |
obj |
fn() |
undefined in strict mode and modules; the global object in sloppy scripts |
new Fn() |
The new object |
fn.call(x, …) / fn.apply(x, [...]) |
x |
fn.bind(x) |
A new function permanently bound to x |
| Arrow function | this of the enclosing scope |
DOM event handler (el.onclick = function(){}) |
The element |
The classic bug is passing a method as a callback, which loses its receiver:
class Counter { count = 0; inc() { this.count++; } }
const c = new Counter();
setTimeout(c.inc, 100); // TypeError: `this` is undefined inside inc
setTimeout(() => c.inc(), 100); // fix 1: arrow wrapper
setTimeout(c.inc.bind(c), 100); // fix 2: bind
class C2 { count = 0; inc = () => { this.count++; }; } // fix 3: arrow class field (one copy per instance)
Java, Go, Rust and C++ bind methods to their receiver statically (c::inc in Java, method values in Go, c.inc closures in C++). JavaScript is the odd one out, and the reason is historical: functions are just properties.
Destructuring
Destructuring unpacks values from arrays and objects into variables. It's similar to Rust's and Java's record patterns, though without exhaustiveness checks:
const [first, , third = 0, ...rest] = [10, 20, 30, 40]; // 10, 30, [40]
const { name, address: { city } = {}, role = "user", ...others } = user;
function draw({ x = 0, y = 0, colour = "black" } = {}) { … } // named, optional, defaulted params
draw({ y: 5 });
[a, b] = [b, a]; // swap
for (const [key, value] of Object.entries(obj)) { … }
const { data: rows } = await res.json(); // rename while destructuring
Defaults apply only when the value is undefined, not null. Destructuring null or undefined throws, so guard with defaults (= {}) or optional chaining.
Spread and rest
... means spread (expand an iterable or object into elements or properties) in calls and literals, and rest (collect the remaining items) in parameters and destructuring:
const merged = { ...defaults, ...options, retries: 3 }; // later keys win: shallow merge
const copy = [...xs]; // shallow copy
Math.max(...xs); // spread arguments (beware huge arrays: stack limits)
const { password, ...safeUser } = user; // rest: omit a key
Spreading is shallow. Nested objects are still shared, and that causes subtle state bugs in React and Redux (chapter 25). Use structuredClone for deep copies, or immutable update helpers such as Immer.
Optional chaining and nullish coalescing
const city = order?.customer?.address?.city; // undefined instead of TypeError if anything is null/undefined
const first = list?.[0]; // optional index
onDone?.(result); // call only if defined
const pageSize = options.pageSize ?? 20; // ?? uses the default only for null/undefined
const pageSize2 = options.pageSize || 20; // || also replaces 0, "", false: usually a bug for numbers
user.nickname ??= user.name; // logical assignment: ??=, ||=, &&=
?? versus || is a classic bug. count || 10 turns a legitimate 0 into 10. These operators are JavaScript's answer to null safety. Java has Optional and Kotlin has ?./?:, while Rust and Zig make absence part of the type (Vol. 1 ch. 2). TypeScript's strictNullChecks (chapter 16) brings that compile-time checking to JavaScript.
Execution: scope, closures and contexts
Execution contexts and the call stack
Every time code runs, the engine creates an execution context: one for the script or module, and one per function call. Each context holds:
- A lexical environment: the variable bindings for this scope, plus a link to the outer environment.
- The
thisbinding. - The code being executed.
Contexts are pushed onto the call stack, the same stack-of-frames idea as in Vol. 1 ch. 7, and popped on return. Exceeding the engine's stack limit (roughly 10,000 frames, depending on frame size) throws RangeError: Maximum call stack size exceeded. JavaScript has no guaranteed tail calls in practice: ES2015 specified them, but only Safari implemented them. Deep recursion over user data needs an explicit stack (Vol. 1 ch. 4).
Scope and lexical environments
JavaScript is lexically scoped (Vol. 1 ch. 2). Each lexical environment points to its parent, and a variable lookup walks the chain outward until the name is found, ending at the global environment. If the name isn't found, reading throws a ReferenceError (and in sloppy mode, assigning creates an accidental global).
Scope levels:
- Global scope: in classic scripts, top-level
varand function declarations become properties ofwindow. Top-levelletandconstare global but not onwindow. - Module scope: each ES module has its own top-level scope, so nothing leaks to global. This is one of the best reasons to use modules.
- Function scope:
varand function declarations. - Block scope:
let,constandclassinside any{ … }.
Hoisting and the temporal dead zone
Before running a scope, the engine creates bindings for every declaration in it. This is hoisting:
console.log(a); // undefined: var is hoisted AND initialised to undefined
var a = 1;
greet(); // works: function declarations are hoisted with their body
function greet() { console.log("hi"); }
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 2; // let/const/class are hoisted but UNINITIALISED until this line runs
The span between entering the scope and the declaration line is the temporal dead zone (TDZ). Touching the binding there throws. That turns "used before initialised" from a silent undefined into a loud error, similar to Java's definite-assignment check (Vol. 1 ch. 2), but at run time. It also explains a subtle shadowing case:
let x = 1;
{
console.log(x); // ReferenceError, not 1: the inner x is hoisted and shadows the outer one in its TDZ
let x = 2;
}
Closures
A closure is a function together with the lexical environment it was created in. The function keeps that environment alive and can read and write its variables after the outer function has returned. The concept is the same as in Vol. 1 ch. 2, but in JavaScript captures are always by reference to the binding, like Go and unlike Java's copies of effectively-final values:
function makeCounter() {
let count = 0; // lives on after makeCounter returns
return {
inc: () => ++count,
get: () => count,
};
}
const c = makeCounter();
c.inc(); c.inc(); c.get(); // 2: `count` is private state, reachable only via the closures
Closures give you encapsulation without classes (the module pattern), and they're how callbacks remember their context, how React hooks work (chapter 22), and how memoisation and partial application are written.
The loop-closure bug (Vol. 1 ch. 2 covered Go's version):
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3: one shared `var i`
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 0 1 2: `let` creates a fresh binding per iteration
Stale closures are the React version of the same idea: a callback created during an earlier render keeps seeing that render's state values (chapter 22).
Memory: a closure keeps its entire environment reachable, as far as the engine can tell. A closure stored in a long-lived place, such as a global event listener, a cache or a timer, can keep large objects alive and cause leaks (chapter 27). Remove listeners and clear timers when components unmount.
Objects, prototypes and classes
Prototypes and the prototype chain
JavaScript has prototype-based inheritance (Vol. 1 ch. 2 mentions this lineage, which comes from the Self language). Every object has an internal link, [[Prototype]], to another object or to null. When you read a property that the object doesn't have, the engine looks on its prototype, then the prototype's prototype, and so on up the prototype chain:
const animal = { eat() { return `${this.name} eats`; } };
const dog = Object.create(animal); // dog's prototype is animal
dog.bark = function () { return "woof"; };
const rex = Object.create(dog);
rex.name = "Rex";
rex.eat(); // "Rex eats": found two links up, `this` is rex
Object.getPrototypeOf(rex) === dog; // true
rex.hasOwnProperty("eat"); // false: inherited
Reads walk the chain, but writes create or modify an own property on the target object (they shadow inherited ones), unless the inherited property is a setter or is non-writable. Every function has a .prototype object, and new F() creates an object whose [[Prototype]] is F.prototype. Built-ins work this way too: [].map lives on Array.prototype.
How this compares with class-based languages: in Java and C++, an object's class is a fixed, compile-time blueprint, and methods are found through a vtable (Vol. 1 ch. 2). In JavaScript, the "class" is a live object you can change at run time. Adding a method to Array.prototype changes every array. Never modify built-in prototypes. It's called monkey patching, and it has broken the web before: a library's Array.prototype.flatten stopped TC39 from using the name, so the standard method became flat ("SmooshGate", 2018).
Classes
class syntax (ES2015) is mostly a cleaner way to write prototype-based constructors, with added guarantees: it's always in strict mode, it can't be called without new, and it can extend built-ins properly.
class Animal {
static count = 0; // static field
#secret = "hidden"; // private field: real privacy, enforced by the engine
name; // public field
constructor(name) { this.name = name; Animal.count++; }
eat() { return `${this.name} eats`; } // on Animal.prototype, shared
get shout() { return this.name.toUpperCase(); } // accessor
static create(name) { return new this(name); }
#whisper() { return this.#secret; } // private method
static { /* static initialisation block */ }
}
class Dog extends Animal {
constructor(name, breed) { super(name); this.breed = breed; } // must call super() before `this`
eat() { return `${super.eat()} kibble`; } // override + super call
}
const d = new Dog("Rex", "lab");
d instanceof Animal; // true: checks the prototype chain
typeof Dog; // "function": a class is still a function
Compared with Java: there's no method overloading, there are no interfaces (TypeScript adds compile-time ones), and there's no protected (only #private, with TypeScript adding a compile-time private/protected). Composition over inheritance (Vol. 1 ch. 2) applies even more strongly in UI code. React moved from class components to functions and hooks largely for that reason.
Property descriptors
Every property has a descriptor that controls its behaviour:
- Data property:
value,writable,enumerable,configurable. - Accessor property:
get,set,enumerable,configurable.
const cfg = {};
Object.defineProperty(cfg, "version", { value: "1.0", writable: false, enumerable: true, configurable: false });
cfg.version = "2.0"; // silently ignored (TypeError in strict mode)
Object.getOwnPropertyDescriptor(cfg, "version");
Object.freeze(obj); // no adds, deletes or changes (shallow); Object.isFrozen
Object.seal(obj); // no adds or deletes; values still writable
Object.preventExtensions(obj); // no adds
Non-enumerable properties are skipped by for…in, Object.keys and JSON.stringify. That's why built-in methods don't show up when you iterate an array's keys.
Getters and setters
Accessors run code when a property is read or written, which is useful for computed values, validation and lazy initialisation:
class Temperature {
#celsius = 0;
get fahrenheit() { return this.#celsius * 9 / 5 + 32; }
set fahrenheit(f) {
if (typeof f !== "number" || Number.isNaN(f)) throw new TypeError("number required");
this.#celsius = (f - 32) * 5 / 9;
}
}
const t = new Temperature();
t.fahrenheit = 212; // runs the setter
t.fahrenheit; // 212, computed
This is the same idea as C# properties or Kotlin's get()/set(), which Java simulates with getter and setter methods. Vue 2 implemented its reactivity with getters and setters, and Vue 3, MobX and Solid use Proxies and signals (chapter 25).
Symbols
A symbol is a unique, unforgeable primitive value, used as a property key that can't collide with anyone else's:
const id = Symbol("id"); // description is for debugging only
user[id] = 123; // won't clash with a library's "id"; skipped by JSON.stringify and for…in
Symbol("x") === Symbol("x"); // false
Symbol.for("app.key") === Symbol.for("app.key"); // true: global registry
Well-known symbols are the language's hooks, the equivalent of implementing Java interfaces or Rust traits for built-in protocols:
| Symbol | Lets an object… | Like |
|---|---|---|
Symbol.iterator |
Work with for…of, spread and destructuring |
Java Iterable, Rust IntoIterator |
Symbol.asyncIterator |
Work with for await…of |
Rust Stream |
Symbol.toPrimitive |
Control conversion to number or string | |
Symbol.hasInstance |
Customise instanceof |
|
Symbol.dispose / Symbol.asyncDispose |
Work with using declarations (explicit resource management) |
Java try-with-resources, Rust Drop, Go defer |
// Explicit resource management (a late-stage TC39 proposal shipping in Chromium and Firefox; TypeScript 5.2+ compiles it)
{
using conn = await openConnection(); // conn[Symbol.dispose]() runs when the block exits, even on throw
await conn.query("…");
}
Private fields
#private fields and methods are truly private. They're enforced by the engine, inaccessible through reflection or Proxy, and invisible outside the class body, unlike TypeScript's private, which only exists at compile time, and the old _underscore convention. #x in obj checks whether an object has the field, which works as a brand check. Private fields are per class: subclasses can't read their parent's #fields, much like Java's private. One consequence: Proxy-wrapping an object with private fields breaks method calls that use them, because the proxy isn't the object that holds the fields.
Reflection
JavaScript was always reflective, since objects are dynamic maps. ES2015 tidied this into the Reflect namespace and Proxy objects (covered under advanced topics):
Reflect.ownKeys(obj); // all own keys, strings and symbols, including non-enumerable
Reflect.has(obj, "x"); // the `in` operator as a function
Reflect.get(obj, "x", receiver); // property read with an explicit `this` for getters
Reflect.defineProperty(obj, "x", d); // returns a boolean instead of throwing
Reflect.apply(fn, thisArg, args);
Reflect.construct(Cls, args);
Compared with Java reflection (Class.getMethods, Method.invoke, used heavily by Spring, Vol. 3), JavaScript reflection is cheap and pervasive. The contrast is decorators: JavaScript's standard decorators (TC39 stage 3, supported by TypeScript 5.0+ and by Babel) are functions applied to classes, methods, fields and accessors, while Angular and NestJS have long used TypeScript's older experimental decorators with reflect-metadata.
Asynchronous JavaScript
Why asynchronous
The page has one main thread (chapter 12). If it waited for a 300 ms network response, nothing else (scrolling, typing, rendering) could happen. So JavaScript's I/O is non-blocking: you start an operation and provide code to run when it finishes. It's the event-loop model from Vol. 1 ch. 8 (epoll and the reactor pattern), built into the language's runtime. Java's virtual threads and Go's goroutines solve the same problem differently: they let you write blocking code and have the runtime multiplex it. JavaScript makes the waiting explicit in the code instead, with callbacks, then promises, then async/await.
Callbacks
The original style passes a function to be called later:
fs.readFile("config.json", "utf8", (err, data) => { // Node's error-first convention
if (err) return handle(err);
parse(data, (err, cfg) => {
if (err) return handle(err);
connect(cfg, (err, db) => { /* … deeper and deeper: "callback hell" */ });
});
});
Callbacks have three problems: nesting ("the pyramid of doom"), error handling that must be repeated at every level, and inversion of control. You hand your continuation to someone else's code, trusting it to call it exactly once, asynchronously, with the right arguments. A library that sometimes calls back synchronously and sometimes asynchronously ("releasing Zalgo") creates very hard ordering bugs.
Promises
A Promise is an object representing the eventual result of an asynchronous operation. It's in one of three states: pending, fulfilled (with a value) or rejected (with a reason). Once settled, it never changes. It's the same concept as Java's CompletableFuture, C#'s Task and Rust's Future, with one important difference: JavaScript promises are eager. The work starts when the promise is created. Rust futures are lazy and do nothing until polled or awaited.
const p = new Promise((resolve, reject) => {
const id = setTimeout(() => resolve(42), 100);
});
p.then(v => v * 2) // returns a NEW promise: chains flatten
.then(v => fetch(`/api/${v}`)) // returning a promise from .then waits for it
.then(res => res.json())
.catch(err => console.error(err)) // catches a rejection anywhere above
.finally(() => hideSpinner());
Promise.resolve(1); // already fulfilled
Promise.reject(new Error("x"));
const { promise, resolve, reject } = Promise.withResolvers(); // ES2024: a "deferred"
Promise guarantees fix the callback problems: callbacks always run asynchronously (as microtasks), each settles once, errors propagate down the chain like exceptions, and chains compose without nesting.
Unhandled rejections: a rejected promise with no handler fires unhandledrejection in browsers. In Node it crashes the process by default (since Node 15). Always end chains with .catch, or await inside try.
async and await
async/await is syntax over promises that makes asynchronous code read like synchronous code:
async function loadDashboard(userId) {
try {
const user = await getUser(userId); // suspends this function, not the thread
const [orders, prefs] = await Promise.all([ // run independent requests IN PARALLEL
getOrders(user.id),
getPrefs(user.id),
]);
return { user, orders, prefs };
} catch (err) {
log.error("dashboard failed", { userId, err });
throw err; // rethrow, or return a fallback
}
}
An async function always returns a promise. await pauses that function and lets the event loop run other work, then resumes it as a microtask when the promise settles. Under the hood the engine turns the function into a state machine, like a generator. That's the same transformation Rust (Vol. 1 ch. 8) and C# perform, and comparable to what Kotlin coroutines do.
Top-level await works in ES modules. Forgetting await returns a pending promise instead of the value, and the TypeScript/ESLint rules no-floating-promises and require-await catch it.
Promise combinators
| Combinator | Settles when | Result | Use |
|---|---|---|---|
Promise.all(ps) |
All fulfil, or the first rejects | Array of values, in input order | Independent requests that are all required |
Promise.allSettled(ps) |
All settle | [{status, value \| reason}] |
Best-effort batches: report each outcome |
Promise.race(ps) |
The first settles (either way) | That value or reason | Timeouts (prefer AbortSignal.timeout) |
Promise.any(ps) |
The first fulfils; rejects only if all reject (AggregateError) |
First success | Redundant sources, fastest mirror |
Analogues: Java's CompletableFuture.allOf/anyOf, Go's errgroup (all with cancellation) and select (race), Rust's futures::join!/try_join!/select!, and Tokio's JoinSet. Note that Promise.all doesn't cancel the other operations when one fails. They keep running. Cancellation is a separate mechanism.
Cancellation and AbortController
Promises can't be cancelled themselves. The platform's cancellation primitive is AbortController / AbortSignal, accepted by fetch, addEventListener, streams, Node APIs and many libraries. It plays the role of Go's context.Context cancellation, Java's Future.cancel and interruption, and C#'s CancellationToken:
const controller = new AbortController();
const { signal } = controller;
fetch("/api/search?q=shoes", { signal })
.then(r => r.json())
.catch(err => { if (err.name === "AbortError") return; throw err; });
controller.abort(); // cancels the request; fetch rejects with AbortError
// Built-in helpers
fetch(url, { signal: AbortSignal.timeout(5000) }); // time out after 5 s (rejects with TimeoutError)
const combined = AbortSignal.any([userCancel.signal, AbortSignal.timeout(5000)]);
// Make your own async functions cancellable
async function poll(url, { signal }) {
while (!signal.aborted) {
await fetch(url, { signal });
await new Promise((r, rej) => {
const t = setTimeout(r, 1000);
signal.addEventListener("abort", () => { clearTimeout(t); rej(signal.reason); }, { once: true });
});
}
}
// signal.throwIfAborted() checks at safe points
el.addEventListener("click", handler, { signal }); // abort() removes the listener too
React's useEffect cleanup (chapter 22) and TanStack Query (chapter 25) pass abort signals to cancel requests a component no longer needs.
Timeouts and retries
Every network call needs a timeout, exactly as on the backend (Vol. 1 ch. 9). fetch has none by default, so a hung connection waits as long as the browser or OS allows.
async function fetchWithRetry(url, { retries = 3, timeoutMs = 5000, signal, ...init } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, {
...init,
signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]),
});
if (res.status >= 500 || res.status === 429) throw new RetryableError(res.status);
return res; // 4xx (except 429) are not retried
} catch (err) {
if (signal?.aborted || attempt >= retries || !isRetryable(err)) throw err;
const base = 200 * 2 ** attempt; // exponential backoff…
const delay = Math.random() * base; // …with full jitter
await new Promise(r => setTimeout(r, delay));
}
}
}
The rules are the same as Part III's resilience chapter: retry only idempotent operations (GET, or POST with an idempotency key), use exponential backoff with jitter (so thousands of clients don't retry in lockstep), cap the attempts, respect Retry-After, and don't retry on client errors (4xx).
Race conditions in UI code
JavaScript is single-threaded, so it has no data races in the memory sense. It still has logical race conditions between async operations (Vol. 1 ch. 8's check-then-act, on one thread):
- Out-of-order responses: a user types "sh", then "shoes". The request for "sh" is slower and arrives last, overwriting the correct results. Fixes: abort the previous request, or ignore stale responses with a request ID or sequence number, or use a library that does this (TanStack Query, RxJS
switchMap). - Set-state-after-unmount: a component starts a request, the user navigates away, and the response arrives and updates state that no longer exists. Abort on cleanup.
- Double submission: a user clicks "Pay" twice. Disable the button while the request is pending, and send an idempotency key so the server deduplicates.
- Check-then-act across awaits:
if (!cache.has(k)) { cache.set(k, await load(k)); }lets two callers both load. Store the promise in the cache instead, which coalesces concurrent requests.
// Latest-wins search: abort the previous request whenever a new one starts
let controller;
input.addEventListener("input", async () => {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(input.value)}`, { signal: controller.signal });
render(await res.json());
} catch (e) {
if (e.name !== "AbortError") showError(e);
}
});
The runtime: event loop in depth
The call stack, tasks and microtasks
The event loop (defined in the HTML standard, chapter 12) is the scheduler that decides what JavaScript runs next on the main thread. Its parts:
- The call stack: the synchronous code currently running. It must empty before anything else happens (run-to-completion).
- Task queues (macrotasks): one task at a time, such as a
setTimeoutcallback, a DOM event dispatch, amessageevent, afetchcompletion delivered through events, or parsing a script. There are several task sources, and browsers may prioritise between them (user input is usually first). - The microtask queue: promise reactions (
.thencallbacks,awaitcontinuations),queueMicrotask(fn), andMutationObservercallbacks. It's drained completely after each task, and after each callback when the stack empties, including microtasks queued while draining. - Rendering steps: roughly once per display frame (16.7 ms at 60 Hz, 8.3 ms at 120 Hz), when the browser decides an update is useful.
One iteration of the loop:
Test your model of the loop:
console.log("1 sync");
setTimeout(() => console.log("5 timeout (task)"), 0);
Promise.resolve()
.then(() => console.log("3 microtask"))
.then(() => console.log("4 microtask 2"));
queueMicrotask(() => console.log("3b queueMicrotask"));
requestAnimationFrame(() => console.log("6? rAF (before next paint)"));
console.log("2 sync");
// Output: 1 sync, 2 sync, 3 microtask, 3b queueMicrotask, 4 microtask 2, 5 timeout (task), then rAF
// (rAF vs the timeout order can vary: rAF waits for the next rendering opportunity)
setTimeout(fn, 0) isn't "now". It means "in a later task, after at least the minimum delay". Browsers clamp nested timeouts to at least 4 ms after five levels, and throttle timers in background tabs to once per second or less.
Rendering opportunities
The browser renders between tasks, not during them. Consequences:
// The user never sees "Loading…": both DOM changes happen inside one task, before any render
status.textContent = "Loading…";
heavyComputation(); // 2 seconds of blocking work
status.textContent = "Done";
To get a frame onto the screen before heavy work, you must yield to the event loop (next section), or move the work off the main thread (Web Workers, chapter 29). Ways to schedule work relative to rendering:
| API | Runs | Use for |
|---|---|---|
requestAnimationFrame(cb) |
Just before the next paint, once per frame | Visual updates and JS animations: read layout, then write styles |
queueMicrotask(cb) |
After the current task, before rendering | Batching state updates within the same turn |
setTimeout(cb, 0) / MessageChannel |
A later task | Yielding so rendering and input can happen |
scheduler.postTask(cb, {priority}) |
A task at user-blocking, user-visible or background priority |
Prioritised work (Chromium; polyfill elsewhere) |
scheduler.yield() |
Resume the current async function in a new task, ahead of other queued tasks | Breaking up long tasks without losing your place (Chromium; Firefox in progress) |
requestIdleCallback(cb, {timeout}) |
When the browser is idle in a frame | Non-urgent work: analytics, prefetching (not in Safari by default) |
Long tasks and yielding
A long task is any task over 50 ms. During it the page can't respond to input, so a click waits until the task finishes. That shows up directly in INP (Interaction to Next Paint, chapter 27). The fix is to break work into chunks and yield between them:
async function processAll(items) {
let lastYield = performance.now();
for (const item of items) {
process(item);
if (performance.now() - lastYield > 40) { // stay under the 50 ms long-task budget
await yieldToMain();
lastYield = performance.now();
}
}
}
function yieldToMain() {
if (globalThis.scheduler?.yield) return scheduler.yield();
return new Promise(resolve => setTimeout(resolve, 0)); // fallback
}
Yielding with a microtask (await Promise.resolve()) doesn't help: microtasks run before rendering and input, so the page stays blocked. You must yield to a task.
Microtask starvation: an endless or very long chain of microtasks (recursive .then, or a promise loop that never awaits real I/O) blocks rendering and input just like a long synchronous loop, because the microtask queue must empty before the loop moves on.
The event loop compared
| Runtime | Model |
|---|---|
| Browser JS | One main thread per page, HTML event loop with tasks, microtasks and rendering. Workers are separate threads with their own loops |
| Node.js | libuv event loop with phases (timers → pending callbacks → poll for I/O → check (setImmediate) → close), a thread pool (default 4 threads) for file system, DNS and crypto work, plus process.nextTick (runs before promise microtasks) |
| Java | Thread-per-request or virtual threads (blocking style). Netty and WebFlux use event loops (the reactor pattern). CompletableFuture callbacks run on executor threads |
| Go | Goroutines + netpoller: blocking-style code, the runtime multiplexes. No coloured functions |
| Rust | async fn → lazy futures polled by an executor (Tokio, multi-threaded, work-stealing). Coloured functions, like JS |
| Python | asyncio event loop, coloured functions, single-threaded by default |
JavaScript and Rust share function colouring (async functions can only be awaited from async functions). Java virtual threads and Go goroutines avoid it, at the cost of a runtime that intercepts blocking calls (Vol. 1 ch. 8).
Advanced built-ins
Iterators and generators
The iteration protocol: an object is iterable if it has a [Symbol.iterator]() method returning an iterator, an object with next() that returns { value, done }. Arrays, strings, Maps, Sets, NodeLists and arguments are iterable, so they work with for…of, spread, destructuring, Array.from, Promise.all and new Map(iterable).
Generators are functions that can pause (yield) and resume, producing an iterator automatically. They're JavaScript's equivalent of Python generators, C# yield return, and Go 1.23's range-over-func iterators:
function* range(start, end, step = 1) {
for (let i = start; i < end; i += step) yield i;
}
[...range(0, 10, 3)]; // [0, 3, 6, 9]
function* fibonacci() { // infinite, lazy
let [a, b] = [0, 1];
while (true) { yield a; [a, b] = [b, a + b]; }
}
const firstTen = fibonacci().take(10).toArray(); // Iterator helpers (ES2025): map, filter, take, drop, flatMap, reduce…
class Tree {
*[Symbol.iterator]() { // make a custom structure iterable with in-order traversal
if (this.left) yield* this.left;
yield this.value;
if (this.right) yield* this.right;
}
}
Generators are lazy: values are computed on demand, which allows infinite sequences and pipelines over huge data without intermediate arrays, like Java streams and Rust iterators (Vol. 1 ch. 2). gen.next(value) can also send values in, which is how libraries implemented async/await before it existed (co, redux-saga).
Async iterators
Async iterators produce values over time: next() returns a promise. for await…of consumes them. They model streams naturally: lines of a file, chunks of an HTTP response, messages from a socket, paginated API results.
async function* paginate(url) {
while (url) {
const res = await fetch(url);
const page = await res.json();
yield* page.items;
url = page.next; // stop when there's no next page
}
}
for await (const order of paginate("/api/orders?limit=100")) {
if (order.total > 10_000) { flag(order); break; } // break stops fetching more pages
}
// Streaming a fetch body: ReadableStream is async-iterable (Baseline in modern engines)
const res = await fetch("/api/llm/stream");
const decoder = new TextDecoderStream();
for await (const chunk of res.body.pipeThrough(decoder)) appendToChat(chunk); // how AI chat UIs stream tokens
Proxy and Reflect
A Proxy wraps an object and intercepts fundamental operations (get, set, has, delete, ownKeys, apply, construct…) through traps. Reflect provides the default behaviour for each trap, so you can forward to it:
function observable(target, onChange) {
return new Proxy(target, {
set(obj, key, value, receiver) {
const old = obj[key];
const ok = Reflect.set(obj, key, value, receiver); // default behaviour
if (ok && old !== value) onChange(key, value, old);
return ok;
},
deleteProperty(obj, key) {
const ok = Reflect.deleteProperty(obj, key);
if (ok) onChange(key, undefined);
return ok;
},
});
}
const state = observable({ count: 0 }, (k, v) => render());
state.count++; // triggers render()
Uses: reactivity systems (Vue 3, MobX and Valtio track reads and writes through proxies), immutable-update drafts (Immer records mutations made to a proxy draft, then produces a new immutable object), validation, default values, API clients that turn api.users.get(1) into requests, mocks in tests, and revocable access (Proxy.revocable). Java's java.lang.reflect.Proxy and Spring's AOP proxies (Vol. 3) are the backend analogue, but they work on interfaces and method calls rather than arbitrary property access. Proxies have a performance cost, and they break identity (proxy !== target) and private fields.
WeakMap, WeakSet and WeakRef
WeakMap keys must be objects (or non-registered symbols), and they're held weakly: if nothing else references a key object, the garbage collector can collect it, and its entry disappears. WeakMaps aren't iterable and have no size, because their contents depend on GC timing.
const metadata = new WeakMap();
function track(el) { metadata.set(el, { clicks: 0 }); } // when el is removed and dropped, its data goes too
// A regular Map would keep every element alive forever: a memory leak
const visited = new WeakSet(); // "have I seen this object?" without preventing its collection
Uses: private per-object data (the pre-#private technique), caches keyed by objects (memoising a function of a DOM node or a request object), and tracking processed objects in graph traversals. WeakRef and FinalizationRegistry give lower-level weak references and cleanup callbacks. Their timing is unpredictable, so avoid them for correctness logic (Java's WeakReference and Cleaner carry the same warning).
TypedArray, ArrayBuffer and DataView
JavaScript arrays hold arbitrary values. For binary data, meaning raw bytes from files, networks, images, audio, WebGL, WebGPU and WebAssembly memory, there's a lower-level family:
ArrayBuffer: a fixed-length block of raw bytes, likemalloc(n)in C, but zeroed and bounds-checked. It's resizable since ES2024 (new ArrayBuffer(n, { maxByteLength })).- Typed arrays: views that interpret a buffer as numbers of one type:
Uint8Array,Int16Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,Uint8ClampedArray(canvas pixels). They behave like C arrays: fixed type, contiguous, fast, and platform-endian (little-endian on every common device). DataView: reads and writes mixed types at arbitrary byte offsets with explicit endianness, which is what you need to parse binary protocols and file formats (Vol. 1 ch. 6).
const buf = new ArrayBuffer(8);
const bytes = new Uint8Array(buf); // view 1: 8 bytes
const words = new Uint32Array(buf); // view 2: 2 × u32 over the SAME memory
words[0] = 0x0A0B0C0D;
bytes[0]; // 0x0D on little-endian machines (Vol. 1 ch. 6)
const view = new DataView(buf);
view.setUint32(4, 0x0A0B0C0D, false); // big-endian (network order) explicitly
view.getUint16(4, false); // 0x0A0B
// Parse a PNG header: 8-byte signature, then IHDR width/height as big-endian u32
const file = new Uint8Array(await blob.arrayBuffer());
const dv = new DataView(file.buffer);
const width = dv.getUint32(16, false), height = dv.getUint32(20, false);
new TextEncoder().encode("é"); // Uint8Array [0xC3, 0xA9]: UTF-8 bytes
new TextDecoder("utf-8").decode(bytes);
Uint8Array.fromBase64?.("SGk="); // Base64 helpers (ES2026): toBase64(), fromHex(), toHex()
WebAssembly memory is an ArrayBuffer, so JavaScript and Rust, C++ or Zig code compiled to Wasm exchange data by reading and writing typed-array views over it (chapter 29). SharedArrayBuffer plus Atomics gives real shared memory between workers, with the same memory-model concepts as Vol. 1 ch. 8, and requires cross-origin isolation.
Structured clone
The structured clone algorithm deep-copies values across boundaries. postMessage to workers and iframes, IndexedDB storage, history.pushState state, and BroadcastChannel all use it, and structuredClone(value) exposes it directly.
| Clones | Doesn't clone (throws DataCloneError or drops it) |
|---|---|
| Primitives (except symbols), plain objects, arrays | Functions, symbols |
Date, RegExp, Map, Set, ArrayBuffer, typed arrays, Blob, File, ImageData, Error types |
DOM nodes |
| Cycles and shared references (preserved) | Class identity: a class User instance arrives as a plain object (the prototype is lost) |
BigInt, boxed primitives |
Getters and setters (copied as values), property descriptors, private fields |
const copy = structuredClone(original); // better than JSON.parse(JSON.stringify(x))
worker.postMessage(bigBuffer, [bigBuffer]); // TRANSFER instead of copy: zero-copy, sender loses access
Compared with JSON.parse(JSON.stringify(x)), structured clone keeps Date, Map, Set, undefined, typed arrays and cycles. The JSON round-trip turns dates into strings, drops undefined and Maps, and throws on cycles. Transferables (ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, streams) move ownership instead of copying, which is the same idea as Rust's move semantics (Vol. 1 ch. 2), applied between threads.
Lab: JavaScript's runtime, measured
The first two experiments ran in Chromium 153 (headless, via Playwright); the others in Node 22. They target the three things that cause most real JavaScript bugs: ordering, blocking and concurrency.
Experiment 1: the event loop's exact order
One function queues work in every way the browser offers, then reports the order things actually ran:
log.push("sync 1");
setTimeout(() => log.push("timeout"), 0);
requestAnimationFrame(() => log.push("animation frame"));
queueMicrotask(() => log.push("microtask"));
Promise.resolve().then(() => { log.push("promise then"); Promise.resolve().then(() => log.push("nested microtask")); });
(async () => { log.push("async fn body (sync part)"); await null; log.push("after await"); })();
log.push("sync 2");
1. sync 1
2. async fn body (sync part)
3. sync 2
4. microtask
5. promise then
6. after await
7. nested microtask
8. timeout
9. animation frame
Reading it with the model from the full-depth section:
- Synchronous code runs to completion first (1–3). Note line 2: an
asyncfunction runs synchronously until its firstawait. - Then the microtask queue drains completely, in the order things were queued (4–6), including microtasks queued by microtasks (7).
awaitresumes as a microtask, which is why "after await" fits between the promise callbacks. - Only then does the loop take the next task: the timer (8).
- Animation frames run just before the browser renders, at most once per frame (about 16.7 ms at 60 Hz), so here the 0 ms timer won. Don't rely on the order between a timer and
requestAnimationFrame: it depends on when the next frame falls.
The practical rule: a microtask loop that keeps queuing microtasks starves everything else (no timers, no rendering, no input), exactly like a while (true).
Experiment 2: a long task versus yielding
A page runs 300 ms of JavaScript work. Playwright sends a real mouse click on a button 40 ms into it, and the button's handler records when it finally ran. The same work is run two ways: as one long task, and as 60 slices of 5 ms with await scheduler.yield() between them:
const spin = ms => { const end = performance.now() + ms; while (performance.now() < end) {} };
if (mode === "one long task") spin(300);
else for (let i = 0; i < 60; i++) { spin(5); await scheduler.yield(); }
one long task work took 300 ms | click waited 260 ms before its handler ran
chunked + scheduler.yield() work took 305 ms | click waited 2 ms before its handler ran
The total work barely changed (5 ms of yielding overhead), but the click went from waiting a quarter of a second, which users feel as a frozen page, to being handled almost instantly. This is what Interaction to Next Paint (INP, chapter 27) measures, and why the browser defines a long task as anything over 50 ms. scheduler.yield() (Chromium since 2024, Firefox since 2025) gives the browser a chance to handle input and render, then resumes your work at a higher priority than ordinary new tasks; the classic fallback is await new Promise(r => setTimeout(r, 0)). For work that can't be sliced, move it to a Web Worker (chapter 29).
Experiment 3: out-of-order responses in search-as-you-type
A user types "dosa" one letter every 30 ms; each keystroke fetches results. The test server answers the queries at different speeds (300, 50, 120 and 80 ms), as real servers do. Three versions of the search code:
// naive
search = (q, render) => fetch(`/?q=${q}`).then(r => r.json()).then(render);
// fix 1: abort the previous request
search = (q, render) => {
controller?.abort(); controller = new AbortController();
fetch(`/?q=${q}`, { signal: controller.signal }).then(r => r.json()).then(render)
.catch(e => { if (e.name !== "AbortError") throw e; });
};
// fix 2: ignore stale responses
search = (q, render) => {
const id = ++latest;
fetch(`/?q=${q}`).then(r => r.json()).then(d => { if (id === latest) render(d); });
};
naive rendered in order: do → dosa → dos → d final screen shows results for "d"
AbortController rendered in order: dosa final screen shows results for "dosa"
latest-request guard rendered in order: dosa final screen shows results for "dosa"
The naive version flickered through four result sets and ended on the wrong one: the slow response for "d" arrived last and overwrote everything. Nothing threw an error; the bug only appears with real network timing, which is why it's so common. Aborting also saves server and network work; the guard is the fallback when the async operation can't be cancelled. Frameworks bake in one or the other (React Query and Angular's switchMap cancel; React's effect cleanup pattern guards).
Experiment 4: numbers and conversions that surprise
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 + 1, 9007199254740993n + 1n);
console.log((1234.5).toLocaleString("en-IN"), (0.615).toFixed(2), (1.005).toFixed(2), Math.round(1.005 * 100) / 100);
console.log(parseInt("08"), parseInt("12px"), Number("12px"), Number(""), Number(" 42 "), +true);
console.log([1, 2, 3].map(parseInt));
9007199254740991 9007199254740992 9007199254740994n
1,234.5 0.61 1.00 1
8 12 NaN 0 42 1
[ 1, NaN, NaN ]
- Integers above 2⁵³ − 1 aren't exact:
2 ** 53 + 1printed as 2⁵³. Database IDs from a 64-bit column must travel as strings orBigInt, or two different IDs can become equal in the browser (a real bug in several public APIs). toFixedrounds the binary value: 0.615 is stored as 0.61499999…, so it rounds down, and 1.005 becomes1.00. For money, work in integer paise and format withIntl.NumberFormat.parseIntreads digits until it can't ("12px"→ 12);Numberrequires the whole string to be numeric (→NaN) but treats""as 0. Choose deliberately, and validate.[1, 2, 3].map(parseInt)callsparseInt("2", 1)andparseInt("3", 2)becausemappasses the index as the second argument, whichparseInttakes as the radix. Pass an arrow function:.map(s => parseInt(s, 10)).
Try it yourself
- Add a
MessageChannelmessage and asetTimeout(…, 0)to experiment 1. Which runs first in Chromium? Why do frameworks useMessageChannelto schedule work? - In experiment 2, slice the work into 50 ms chunks instead of 5 ms. How long does the click wait now? Find the largest chunk size that keeps the wait under 50 ms.
- Write a
searchWithDebouncethat waits until the user stops typing for 150 ms before fetching. Combine it withAbortController. How many requests does typing "dosa" send now? - Fetch
{"id": 9007199254740993}withresponse.json()and print the id. Then parse it safely (hint:JSON.parsewith a reviver and the newcontext.sourceargument, or ask the server for strings).
Revision sheet: JavaScript
Key ideas
- Seven primitive types (number, bigint, string, boolean, undefined, null, symbol) plus objects; primitives are immutable and compared by value, objects by reference.
constby default,letwhen reassigning; block scope; the temporal dead zone;varis function-scoped and hoisted.- Coercion:
==,+with strings, truthiness; use===, explicitNumber()/String(),??and?.. - Functions are values; closures capture variables (not values) from their lexical scope; arrow functions take
thisfrom their surroundings, ordinary functions from how they're called. - Prototypes: property lookup walks the prototype chain;
classis syntax over prototypes with real private fields (#x). - Event loop: run a task to completion → drain all microtasks → maybe render (rAF, style, layout, paint) → next task. Promises,
awaitandqueueMicrotaskare microtasks; timers, events and messages are tasks. - Promises: pending → fulfilled or rejected, once;
thencallbacks always run asynchronously; combinatorsall(fail fast),allSettled,race,any; cancel withAbortController/AbortSignal.timeout/AbortSignal.any. fetchrejects only on network failure or abort; checkresponse.ok.- Iterators and generators power
for…of, spread and destructuring; async iterators powerfor await. - Modules: static
import/export, live bindings, evaluated once,import()for lazy loading, top-levelawait. - Built-ins worth knowing:
Map/Set(any keys, insertion order),WeakMap/WeakRef, typed arrays,structuredClone,Intl,Temporal(arriving in browsers; replacesDate's pitfalls).
Numbers to remember
- Safe integers: ±(2⁵³ − 1) = ±9,007,199,254,740,991.
- Long task: over 50 ms. A 60 Hz frame: about 16.7 ms.
setTimeoutnesting clamp: at least 4 ms after five nested levels; background tabs throttle timers to once a second or less.
Pitfalls
==, string concatenation from form values,sort()without a comparator,parseIntwithout a radix or as amapcallback.thislost when passing a method as a callback (button.addEventListener("click", obj.method)).- Awaiting independent work sequentially; forgetting
await(a promise is truthy); unhandled rejections. - Race conditions from out-of-order responses; no timeouts on fetch.
- Mutating shared objects and arrays (
sort,reverse,splicemutate;toSorted,toReversed,withdon't). - Money in floating point; 64-bit IDs as numbers.
- Long synchronous loops on the main thread.
Glossary
- Coercion: implicit conversion between types.
- Closure: a function plus the variables it captured from its creation scope.
- Prototype chain: the linked objects searched for properties not found on an object itself.
- Microtask: a job run right after the current task, before rendering (promise reactions,
awaitcontinuations). - Long task: a task that keeps the main thread busy for more than 50 ms.
- Live binding: an imported name that reflects the exporting module's current value.