Workbench / Volume 2 Companion: The Web Frontend
V2·15
JavaScript
Companion to Volume 2, chapter 15: how the language, execution and the runtime connect; new angles (closures as a tiffin box packed at home, the event loop as a single-counter kitchen, promises as order tokens, modules as a shared kitchen pantry); what the chapter simplifies, measured in Node 22: a boolean comparator that leaves an array completely unsorted, `return p` inside `try` that doesn't catch, an unused closure that keeps 160 MB alive, `await` chains that keep their stack traces while callbacks lose them, a circular import that crashes or not depending on which file is loaded first, and class instances that come back from `structuredClone` without their methods; the theory behind it; how lodash's `debounce` is written (and why it calls `setTimeout` five times for eleven keystrokes); four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 15 has three strands. The language: values and types, coercion, objects and arrays as references, functions as values, destructuring and spread, modules. Execution: the call stack and execution contexts, scope and closures, hoisting and the temporal dead zone, this, prototypes and classes. Asynchrony and the runtime: callbacks, promises, async/await, combinators and cancellation, the event loop's tasks and microtasks, and rendering between them.
The links worth remembering:
- Closures are how JavaScript remembers. A function keeps the scope it was created in. Event handlers, callbacks, debounced functions and module state all rely on it, and it's also how JavaScript leaks memory (Gaps 3).
awaitis a promise in disguise. Everyawaitsplits a function: the rest runs later, in a microtask. Everything about ordering, error handling andtry/catchin async code follows from that (Gaps 2).- One thread does everything. Script, rendering and input share one thread per page. A long task blocks all three, and the event loop's rules (all microtasks before the next task or render) decide what the user sees and when.
Explain it differently
1. A closure is a tiffin box packed at home. When a function is created, it gets a box with everything from its surroundings that it (or any sibling packed at the same time) might need. Wherever the function goes (a click handler, a timer, another module), it opens the box and finds those variables, still live, still shared with anyone else holding the same box. The surprise is that sibling functions share one box (Gaps 3).
2. The event loop is a single-counter kitchen. One cook (the main thread) works through order slips (tasks) one at a time. Between slips, they finish every "just one more thing" note stuck to the counter (microtasks), and only then glance up to update the display board (rendering). A slip that takes 2 seconds freezes the board for 2 seconds; a stack of "one more thing" notes that keeps growing means the board is never updated at all.
3. A promise is an order token. You order a dosa and get a token. The token isn't the dosa, but you can say what you'll do when it's ready (then), and it will only ever be called once: ready, or "sorry, we're out" (rejected). await is standing at the counter with the token, except that the rest of the kitchen keeps working while you wait.
4. this is decided by who's holding the phone. A method doesn't own this; the caller hands it over at call time. kitchen.hello() means "kitchen is calling"; passing kitchen.hello to a timer hands the phone to the timer, which isn't the kitchen. Arrow functions don't take calls themselves; they use whoever was on the line where they were written.
5. Prototypes are asking your senior. When an object doesn't know a property, it asks its prototype, which asks its prototype, up to Object.prototype. Classes are a polite way to set up who reports to whom. Nothing is copied; changing a senior's answer changes it for every junior who asks.
6. Modules are a shared kitchen pantry. Every file that imports money.js gets the same jars (the same module instance, evaluated once). An export let is a jar, not a photo of a jar: if the exporting module refills it, importers see the new contents (live bindings). And if two pantries each need something from the other before they're stocked, someone finds an empty shelf (Gaps 5).
7. Coercion is a helpful clerk who never says "I don't understand". Hand == a string and a number and the clerk converts one into the other rather than refuse, following a long rulebook. It's helpful until it isn't. === is the clerk who refuses to compare things of different types.
8. AbortController is the "cancel my order" button with a receipt. The controller is the button; its signal is a receipt you hand to every worker on the order (fetch, timers, your own code). Pressing the button tells everyone holding the receipt at once, and each decides how to stop. One button can cancel a whole chain, which is how search-as-you-type drops stale requests.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from Node 22.22.
1. "Pass a comparator to sort": one that returns a negative number. The chapter (and Chapter Exercises P4) show sort() without a comparator sorting numbers as strings. The next bug is a comparator that returns a boolean, a habit from languages where a > b is how you sort:
boolean comparator (a > b): 8950 3000 4000 18000 4500 8000 7000 6000 5500 5000 3000 12000
number comparator (a - b): 3000 3000 4000 4500 5000 5500 6000 7000 8000 8950 12000 18000
30 numbers, boolean comparator, sorted? false
The prices came back in their original order. A comparator must return negative, zero or positive; true and false become 1 and 0, so it never says "a comes first", and V8's sort (binary insertion for short arrays, TimSort beyond) never moves anything left. Other engines and older V8 versions, whose sorts only checked "greater than zero", produced sorted or partly sorted results, which is worse: it looks like it works in testing (drill D1).
2. "async functions catch errors with try/catch": only errors that happen while they're waiting. The chapter shows try { await … } catch. Leave out the await in a return, and the error escapes:
async function withReturn() { try { return fetchMenu(); } catch { return 'cached menu'; } }
async function withReturnAwait() { try { return await fetchMenu(); } catch { return 'cached menu'; } }
return p -> REJECTED: network down
return await p -> cached menu
return fetchMenu() hands the promise back to the caller and leaves the try block immediately; the rejection happens later, outside it. return await waits inside the try, so the catch runs. Outside a try, return await is redundant; inside one, it's the difference between a fallback and an error page (drill D2). ESLint's @typescript-eslint/return-await with in-try-catch enforces exactly this.
3. Memory leaks: closures share one scope object, so an unused closure can keep data alive. Chapter Exercises S1 finds listeners that are never removed. This one is subtler, from how V8 implements closures: all closures created in one function share one context object holding every variable any of them uses. Two versions of a dish card builder, each keeping 200 small click handlers that use only i:
function cardA(i) { const snapshot = new Array(100_000).fill(i); console.assert(snapshot.length > 0); return () => i; }
function cardB(i) { const snapshot = new Array(100_000).fill(i);
const log = () => console.log(snapshot.length); // created, never kept
return () => i; }
A: handler only 200 handlers kept: heap +0.0 MB
B: handler + an unused closure 200 handlers kept: heap +160.0 MB
In B, log uses snapshot, so snapshot goes into the shared context; the handler we keep holds that context, so every snapshot stays alive (0.8 MB × 200). log itself was garbage the moment the function returned. The fix is to keep large data out of scopes that create long-lived closures (build in one function, return a handler from another), or to drop the reference (snapshot = null) when done. Heap snapshots show it as "context" retaining the arrays (drill D3).
4. Error handling: await keeps the stack trace; callbacks lose it. The chapter leaves out observability. The same failure, reached through an await chain and through callbacks:
--- await chain
Error: menu service returned 503
at getMenu (file:///tmp/exp15/stack.mjs:1:76)
at async search (file:///tmp/exp15/stack.mjs:2:35)
at async onInput (file:///tmp/exp15/stack.mjs:3:28)
at async file:///tmp/exp15/stack.mjs:4:7
--- callbacks
Error: menu service returned 503
at Timeout._onTimeout (file:///tmp/exp15/stack.mjs:5:46)
at listOnTimeout (node:internal/timers:588:17)
at process.processTimers (node:internal/timers:523:7)
V8 reconstructs await chains ("zero-cost async stack traces": the at async frames), because each awaiting function is suspended and still known. A callback run by a timer has no caller to show: the stack starts at the timer. In production, the first trace tells you which user action failed; the second tells you only that "a timer fired". It's a concrete reason to write async code with await, and to wrap callback APIs into promises at the lowest level so the rest of the code keeps its traces. Chromium DevTools shows async frames for callbacks too, but only while DevTools is open; error reports from users' browsers don't have them.
5. Modules: circular imports crash or don't, depending on which file is loaded first. The chapter mentions live bindings. Two modules that import each other, money.mjs (exports ZERO, imports DEFAULT_DISH) and menu.mjs (exports DEFAULT_DISH = { price: ZERO }, imports ZERO):
--- ESM, entry main.mjs (imports money.mjs):
ReferenceError: Cannot access 'ZERO' before initialization
at file:///tmp/exp15/circ/menu.mjs:2:52
exit 1
--- ESM, entry main2.mjs (imports menu.mjs first):
exit 0
--- CommonJS, entry money.cjs:
menu.cjs sees ZERO = undefined
(node:5385) Warning: Accessing non-existent property 'ZERO' of module exports inside circular dependency
ES modules evaluate dependencies first, depth-first: importing money first means menu runs before money has initialised ZERO, which is still in its temporal dead zone, so it throws. Import menu first and the order flips: no error. The same code works or crashes depending on import order elsewhere in the app (a new import in an unrelated file can break it). CommonJS doesn't throw: require returns the half-built exports object, so ZERO is silently undefined and the dish's price is undefined, found much later. Break cycles by moving shared values to a third module both import (drill D4).
6. structuredClone and postMessage copy data, not classes. Chapter Exercises P4 shows structuredClone keeping Map, Date and cycles. It doesn't keep your classes:
copy: { paise: 8950 } | instanceof Money: false | typeof copy.plus: undefined
via postMessage: { paise: 8950 } | plus: undefined
A Money sent to a worker (chapter 15's C2) arrives as a plain object, and m.plus(...) throws. The structured clone algorithm copies own data properties and built-in types; prototypes don't cross. Send plain data and rebuild instances on the other side (Money.from(data)), the same rule as JSON across the network.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
"(a, b) => a > b sorts ascending." |
It must return a negative number to move anything; a boolean leaves the array unsorted. | Gaps 1; drill D1 |
"try/catch in an async function catches everything inside it." |
Not a promise returned without await. |
Gaps 2; drill D2 |
| "A closure keeps only the variables it uses." | In V8, all closures from one scope share a context holding every variable any of them uses. | Gaps 3; drill D3 |
| "Async code loses stack traces." | await chains keep them; callbacks and timers don't. |
Gaps 4 |
| "Circular imports are fine in ES modules." | They work only if no module uses another's binding during evaluation; the result depends on load order. | Gaps 5; drill D4 |
"structuredClone deep-copies anything." |
Not prototypes, functions, DOM nodes or class instances' methods. | Gaps 6 |
"async makes code run in parallel." |
It runs on the same thread; it only stops blocking while waiting for I/O. | Explain it differently 2 |
Theoretical gaps: the ideas behind the chapter
1. Run-to-completion is the concurrency model. A task, once started, runs to the end before anything else on that thread runs. No locks are needed for ordinary code, because nothing can interrupt it; the cost is that any long task blocks everything. It's the opposite trade-off from Java's shared-memory threads (Volume 1), and it's why JavaScript's concurrency bugs are about ordering across awaits (stale responses, check-then-act across an await), not data races.
2. Every await is a yield point, and state can change across it. Code before and after an await runs in different tasks or microtasks, and anything else can run in between. if (!cache.has(k)) { const v = await load(k); cache.set(k, v); } can load the same key twice. It's the same check-then-act problem as threads, at known points instead of anywhere. Reasoning about async code means reasoning about what can change at each await.
3. Closures and objects are equivalent. A closure is a function with private state; an object is state with functions attached. Anything you can do with one you can do with the other (the module pattern, factories against classes). JavaScript has both, and choosing between them is about readability, not capability; the costs differ only in implementation details like Gaps 3 and the per-instance functions of arrow class fields.
4. Promises are a monad-like abstraction over "a value later". then both maps (return a value) and flattens (return a promise), errors propagate along the chain like exceptions, and async/await is syntax for chaining. That's why a forgotten return inside then, or a forgotten await, breaks the chain: the value or error leaves the pipeline. The same shape appears in Java's CompletableFuture and in Rust's futures.
5. Garbage collection is about reachability, not usefulness. The collector frees what can't be reached from roots (globals, the stack, live closures, registered listeners, timers). Leaks in garbage-collected languages are always "still reachable but no longer needed": a listener list, a cache, a closure's context. Finding a leak means finding the path from a root, which is what heap snapshots' "retainers" view shows.
6. The language evolves by consensus, and never breaks the web. TC39 adds features through stages 0–4, with two implementations required before stage 4. Old behaviour is never removed (var, ==, typeof null === "object"), because existing sites depend on it. That's why JavaScript grows by adding better alternatives (let, ===, ??, Object.hasOwn) rather than fixing originals, and why linters, not the language, are where teams retire the old forms.
Applying it
Code walkthrough
Stage 15 of the TiffinBox build adds search-as-you-type, which needs a debounce. lodash's debounce is the one most codebases have used, directly or copied. Excerpts from lodash-es 4.17.21's debounce.js, installed from npm.
The state
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
The whole debouncer is a closure over these variables (Explain it differently 1). Two timestamps are the key design: lastCallTime (when the debounced function was last called) and lastInvokeTime (when func last actually ran). Everything else is derived from them.
Calling the debounced function
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
A call records its arguments and the time, and starts a timer only if none is running. It never clears and restarts the timer on each call (the textbook debounce does). Instead:
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
When the timer fires, it checks whether wait has really passed since the last call. If calls kept coming, it sleeps again for just the remaining time. The timer is lazy: it's re-armed at most once per wait period, however fast the calls arrive. Note the clock defence: timeSinceLastCall < 0 (the system clock went backwards) is treated as "time's up", the same class of bug Volume 1's stage 5 found in order timestamps. Typing "masala dosa", one key every 80 ms, with wait = 250 ms (real output, counting timer calls):
naive keystrokes: 11 | setTimeout: 11 | clearTimeout: 11
searched: [ 'masala dosa' ]
lodash keystrokes: 11 | setTimeout: 5 | clearTimeout: 0
searched: [ 'masala dosa' ]
Both search once, for the full text. Lodash used 5 timers and no cancellations instead of 22 timer operations. It doesn't matter for one search box; it matters for debounced handlers on scroll or mousemove, which fire 60+ times a second.
Read it yourself
debounced(q)returnsresult. What doesconst r = debouncedSearch('m')give you?- What does
maxWaitchange, and when would search-as-you-type want it?
Debugging drills
D1. "Sort by price" does nothing
The kitchen's dish list has a "sort by price" button. On a phone, it seems to do nothing; a developer says it worked in their test with three dishes. The code: dishes.sort((a, b) => a.price > b.price).
D2. The offline fallback never shows
When the menu service is down, the app should show the cached menu. Instead, users get the error page. The function:
async function loadMenu() {
try { return api.getMenu(); }
catch (e) { return cache.menu(); }
}
D3. Memory grows with every menu refresh
The kitchen display refreshes its menu every minute and rebuilds its dish cards. Memory grows by about 50 MB an hour. Heap snapshots show large arrays retained by (context) from buildCard, but buildCard's click handler only uses the dish id:
function buildCard(dish, allOrdersToday) {
const stats = allOrdersToday.filter(o => o.has(dish.id)); // big
const el = render(dish, stats.length);
el.querySelector('.log').onclick = () => console.table(stats); // a debugging aid
el.onclick = () => openDish(dish.id);
return el;
}
Old cards are removed from the DOM. Why are the arrays still alive?
D4. "Cannot access 'ZERO' before initialization" after an unrelated change
A developer adds import { DEFAULT_DISH } from './menu.js' to money.js for a new helper. Tests pass. In production, the checkout page crashes on load with ReferenceError: Cannot access 'ZERO' before initialization in menu.js. The home page, which imports menu.js directly, works.
Career-oriented
Interview prep
Mid level
Q1. Implement debounce(fn, ms) and explain one bug in a naive implementation.
How to get there. Write the textbook version (clear and set a timer on each call), then examine it: what happens to this, to arguments, to the return value, and to a pending call when the component goes away?
Q2. What's the difference between these, and which would you use to load a dish list, its prices and today's offers?
const a = await getDishes(); const b = await getPrices(); const c = await getOffers();
const [a, b, c] = await Promise.all([getDishes(), getPrices(), getOffers()]);
const r = await Promise.allSettled([getDishes(), getPrices(), getOffers()]);
How to get there. Compare timing (sequential against concurrent), and failure behaviour (one rejection rejects all; allSettled never rejects). Then decide by what the page can do without each piece.
Senior level
Q3. Production error reports from the TiffinBox web app say only TypeError: Cannot read properties of undefined (reading 'paise') at app.min.js:1:48213. How do you make errors actionable?
How to get there. Chapter Exercises leaves error handling and observability out. Work through capture (which errors reach you), context (what was the user doing), and decoding (minified locations). Add stack quality (Gaps 4).
Q4. The team wants to move CPU-heavy work (pricing a large cart with the rules engine) to a Web Worker. What will go wrong, and how do you design it?
How to get there. Think about what crosses the boundary (copied data, no classes, Gaps 6), how requests and responses are matched, cancellation, errors, and whether it's worth it (measure first).
Staff level
Q5. TiffinBox's Java backend team will own parts of the frontend. How do you set them up to write good JavaScript without a long ramp-up?
How to get there. Chapter Exercises S4 explains the event loop to Java engineers; this is the broader plan. Identify where Java intuition misleads (threads, this, equality, numbers, nulls, modules), and decide what to teach, what to automate, and what to prevent with tools.
Q6. A product manager asks: "Can we ship features faster by letting each team use whichever JavaScript libraries they like?" How do you answer?
How to get there. Balance team autonomy against costs that are shared: bundle size on customers' phones, security exposure through dependencies, duplicated solutions, and upgrade work. Propose a policy rather than a yes or no.