Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·15

JavaScript

Exercises for Volume 2, chapter 15: primitives, types and coercion, var/let/const, objects and arrays, functions, destructuring, spread and rest, optional chaining and nullish coalescing; execution contexts, scope, hoisting, the temporal dead zone and closures; prototypes, classes, property descriptors, getters and setters, symbols, private fields and reflection; callbacks, promises, async/await, combinators, cancellation with AbortController, timeouts, retries and UI race conditions; the event loop, rendering and long tasks; iterators, generators, async iterators, Proxy and Reflect, WeakMap and WeakRef, typed arrays and structured clone. 11 theory questions, 11 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

37 exercises · ~18 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. JavaScript punishes guessing, so most exercises are predict-then-run: write down what you think a snippet prints, then run it with Node (node file.mjs) or in the browser console. The outputs in the solutions come from Node 22 in this book's sandbox, whose time zone happens to be Asia/Kolkata, which matters for the date exercises (P4). Files ending in .mjs are ES modules, which run in strict mode: that changed one result (P5), and it's a lesson in itself.

As a Java developer you'll recognise much of the syntax; the exercises concentrate on where JavaScript behaves differently from Java: coercion, this, prototypes, closures over loop variables, single-threaded async, and numbers.

Coverage map.

Chapter component Exercises
primitives, typeof, coercion, equality, truthiness T1, P1
var/let/const, scope, hoisting, TDZ, closures T2, P2
functions and this; arrow functions; bind/call T3, P3
objects, arrays, destructuring, spread/rest, optional chaining, ?? T4, P4
numbers, strings, dates and Intl T5, P4
prototypes, classes, descriptors, getters/setters, symbols, private fields, reflection T6, P5
callbacks, promises, async/await T7, P6
combinators, cancellation, timeouts, retries T8, P7
race conditions in UI code T8, P8
the event loop in depth, rendering, long tasks T9, P9
iterators, generators, async iterators T10, P10
Proxy/Reflect, WeakMap/WeakRef, typed arrays, structured clone T11, P11

Theory

T1. Types and coercion

  1. List JavaScript's primitive types, and explain P1's typeof null → "object", typeof NaN → "number", typeof [] → "object".
  2. P1 printed [] == false true, null == undefined true, null == 0 false, '' == 0 true, '0' == false true, NaN == NaN false, Object.is(NaN, NaN) true, Object.is(0, -0) false. Explain the rules behind == well enough to predict these, and state the team rule.
  3. P1: 1 + '2' is "12", '3' * '4' is 12, [] + [] is "", [1,2] + [3] is "1,23", '5' - 2 is 3. Why does + differ from the other operators?
  4. Which values are falsy? P1 showed [], {} and '0' are truthy. What bug does that cause in code like if (items) or count || 10?

T2. Scope, hoisting and closures

  1. Compare var, let and const: scope, hoisting, redeclaration, and the temporal dead zone (P2: accessing x before let x threw ReferenceError: Cannot access 'x' before initialization). Does const make objects immutable?
  2. P2 scheduled three setTimeouts in a var loop and three in a let loop: var 3, var 3, var 3, let 0, let 1, let 2. Explain with closures and per-iteration bindings.
  3. What is a closure, precisely? Give three everyday uses (private state, factories, event handlers) and one memory leak caused by closures.
  4. Compare JavaScript's closures with Java's lambdas and anonymous classes (chapter 10 of Volume 1, and Volume 3's functional chapter).

T3. this

  1. P3 extracted const f = kitchen.hello and called f(): it returned "Hi from undefined" (in a module, this is undefined, and this?.name avoided a crash). f.call({name: 'Other'}) and kitchen.hello.bind({name: 'Bound'})() worked. State the four rules that decide this, in priority order.
  2. Why do arrow functions fix callbacks (setTimeout(() => this.refresh())) but break object methods (arrow: () => this.name, which gave undefined in P3)?
  3. A React class component or a plain class passes this.handleClick to addEventListener and it fails with "Cannot read properties of undefined". Give two fixes and say which you prefer.

T4. Objects, arrays and copying

  1. P4: Object.keys({b: 1, 2: 'x', a: 1, 1: 'y', '-1': 'z'}) returned ['1', '2', 'b', 'a', '-1']. State the property-order rule, and why you shouldn't rely on object key order for things like sorted menus (use Map or arrays).
  2. P4: after const sp = {...orig}; sp.price.paise = 1, orig.price.paise was also 1. JSON.parse(JSON.stringify(orig)) turned a Date into a string, a Set into {} and dropped an undefined property; structuredClone kept the Date, the Set and the property. Explain shallow vs deep copies and when each method is right.
  3. Explain destructuring with defaults and renaming, rest/spread in calls and objects, optional chaining and ??, with a function formatOrder({id, kitchen: {name: kitchenName} = {}, items = [], note} = {}).
  4. Array methods: which mutate (sort, reverse, splice, push) and which return new arrays (toSorted, toReversed, toSpliced, with, map, filter)? Why does that matter for UI frameworks?

T5. Numbers, strings, dates and Intl

  1. P4: [10, 9, 1, 100, 25].sort() gave [1, 10, 100, 25, 9]; with (a, b) => a - b it was numeric; ['Zebra', 'apple', 'Éclair', 'banana'].sort() put Zebra first and Éclair last, while localeCompare gave apple, banana, Éclair, Zebra. Explain, and give the correct way to sort dish names for Indian users.
  2. P4's numbers: 0.1 + 0.2 → 0.30000000000000004, (1.005).toFixed(2) → "1.00", Math.round(-2.5) → -2, parseInt('1e3') → 1 but Number('1e3') → 1000, Number('') → 0, parseFloat('3.5kg') → 3.5. Explain each and say how to handle money in a JavaScript frontend (Volume 1, chapter 06).
  3. P4's dates (sandbox time zone Asia/Kolkata): new Date('2026-11-14') is midnight UTC; new Date('2026-11-14T00:00') is midnight local (18:30 UTC the previous day); new Date(2026, 10, 14) has month 10 = November; new Date(2026, 1, 31) silently became 3 March. Explain the traps and the safe patterns (and Temporal).
  4. P4's Intl.NumberFormat('en-IN', {style: 'currency', currency: 'INR'}) formatted 123456.5 as ₹1,23,456.50, while en-US gave ₹123,456.50. Why must formatting come from the user's locale, not string concatenation?

T6. Prototypes and classes

  1. Explain the prototype chain: what happens when you read order.add on an instance of class Order? What does Object.keys(order) (P5: [] for an order whose state was in a private field) and typeof Order.prototype.add ("function") tell you?
  2. Compare JavaScript classes with Java classes: fields, methods on the prototype, static, private #fields (P5: #total in o as a brand check), no overloading, single inheritance with extends, and instanceof across realms.
  3. P5: Object.freeze on {price: {paise: 1}, name: 'x'}: assigning frozen.name threw Cannot assign to read only property 'name' (strict mode) while frozen.price.paise = 2 succeeded. Explain property descriptors (writable, enumerable, configurable), freezing, and why sloppy-mode scripts would have failed silently.
  4. What are symbols for (Symbol.iterator, Symbol.toPrimitive, unique keys), and when would you use Reflect and Object.defineProperty?

T7. Promises and async/await

  1. What problem did promises solve over callbacks ("callback hell", inversion of control, error handling)? Describe a promise's states and what then returns.
  2. P6: async function placeOrder() { throw … } returned a Promise, and the error was caught later with .catch. Explain how async and await map onto promises, where errors go, and why await inside try/catch behaves like synchronous code.
  3. P6: three sequential await sleep(100) took 300 ms; Promise.all of three took 100 ms. When must operations be sequential, and when should they run in parallel?
  4. P6: [1,2,3].forEach(async id => { await save(id) }) reported 0 saved immediately afterwards, and 3 saved 80 ms later. Why, and what do you write instead?
  5. P6: an unhandled promise rejection made Node exit with code 1. What happens in browsers, and why should every promise chain end in handling?

T8. Combinators, cancellation and UI races

  1. P7 ran three tasks (100 ms success, 50 ms failure, 150 ms success) through Promise.all (rejected at 50 ms), allSettled (all three results after 150 ms), any (first success at 100 ms) and race (the failure at 51 ms). Give a TiffinBox use for each.
  2. Promises can't be cancelled. How does AbortController give cancellation for fetch, event listeners and your own functions? P7's AbortSignal.timeout(200) aborted a 1,000 ms operation with a TimeoutError after 201 ms.
  3. The chapter's lab showed search-as-you-type rendering results for "d" after "dosa" because responses arrived out of order. Give two fixes, and name two other UI race conditions (double submit, stale component state after navigation).

T9. The event loop, rendering and long tasks

  1. The chapter's lab printed: sync 1, async fn body (sync part), sync 2, microtask, promise then, after await. Explain why the synchronous part of an async function runs immediately and the code after await runs later.
  2. P9 compares a 300 ms long task with the same work chunked using scheduler.yield() (the lab: a click waited 260 ms versus 2 ms). Explain why total work barely changed but responsiveness did, and how this connects to the INP metric.
  3. Compare the browser event loop with Node's (phases, process.nextTick, setImmediate) and with Java's concurrency model (Volume 1, chapter 08). Why is JavaScript code free of data races without locks, and what kind of concurrency bugs does it still have?

T10. Iterators, generators and async iterators

  1. What is the iteration protocol, and what makes for…of, spread and Array.from work on arrays, strings, Maps, Sets and your own objects?
  2. P10 created an infinite generator ids() and took the first five values lazily with another generator, take. Explain how generators pause and resume, and why laziness matters for large or infinite sequences.
  3. What are async iterators and for await…of? Give an example with paginated API results or a streamed response body.

T11. Advanced built-ins

  1. P11's Proxy rejected paise = 1.5 with a TypeError but accepted 100. What are proxies used for (validation, observability in Vue's reactivity, mocking), and what are their costs?
  2. When do you use Map/Set versus objects, and WeakMap/WeakSet/WeakRef/FinalizationRegistry? Give a use for WeakMap that a Map would turn into a memory leak.
  3. What are ArrayBuffer, typed arrays and DataView for in a frontend? Connect them to Volume 1, chapter 06 (byte order, binary formats).
  4. What does structuredClone support, and where else is the structured-clone algorithm used (postMessage, IndexedDB)?

Programming exercises

P1. Coercion: predict, then run

Without running anything, write down the output of: typeof null, typeof NaN, typeof [], typeof function(){}, typeof 10n; [] == false, null == undefined, null == 0, '' == 0, '0' == false, NaN == NaN, Object.is(NaN, NaN), Object.is(0, -0), 0 === -0; Boolean([]), Boolean({}), Boolean(''), Boolean('0'), Boolean(0n); 1 + '2', '3' * '4', [] + [], [1,2] + [3], true + 1, '5' - 2. Then run them in Node and score yourself. Finally, enable ESLint's eqeqeq and no-implicit-coercion on a file of yours and fix what it reports.

P2. Scope, TDZ and the loop closure

Run: (a) try { x; let x = 1; } catch (e) { console.log(e.message) }; (b) a for (var i …) loop and a for (let j …) loop, each scheduling setTimeout(() => out.push(i)), printing out afterwards; (c) a counter() factory returning an increment function, called on two separate counters. Then write a "leaky" component that adds a resize listener with a closure over a 10 MB array and never removes it; create and discard it 20 times and watch memory in DevTools' Memory panel; fix it with an AbortController signal.

P3. this in every situation

Run P3's kitchen object: kitchen.hello(), const f = kitchen.hello; f(), f.call({name: 'Other'}), kitchen.hello.bind({name: 'Bound'})(), and an arrow-function property kitchen.arrow(). Then write a class MenuWidget with a method onClick that uses this.items, register it with button.addEventListener('click', this.onClick) and observe the failure; fix it three ways (bind, class-field arrow, wrapper).

P4. Data, numbers, strings and dates

Predict and run: the key order of {b: 1, 2: 'x', a: 1, 1: 'y', '-1': 'z'}; spread vs JSON vs structuredClone copies of an object with a nested price, a Date, a Set and an undefined property; the default and correct sorts of [10, 9, 1, 100, 25] and ['Zebra', 'apple', 'Éclair', 'banana']; 0.1 + 0.2, (1.005).toFixed(2), (1.255).toFixed(2), Math.round(2.5), Math.round(-2.5), parseInt('08'), parseInt('1e3'), Number('1e3'), Number(''), Number(' 42 '), parseFloat('3.5kg'); Intl.NumberFormat for 123456.5 INR in en-IN, en-US and hi-IN; the four Date cases from T5; and '👍🏽'.length, [...'👍🏽'].length, graphemes with Intl.Segmenter, 'café' === 'café' before and after normalize(), and 'i'.toLocaleUpperCase('tr').

P5. Classes, private fields and freezing

Write class Order with a private #total, a static count, an add(paise) method returning this, a total getter, and a static brand check isOrder(o) using #total in o. Print new Order().add(100).add(50).total, Order.isOrder(o), Order.isOrder({}), Object.keys(o) and typeof Order.prototype.add. Then freeze {price: {paise: 1}, name: 'x'} and try to change both properties, in an .mjs module and in a classic sloppy-mode script.

P6. Promises and async functions

With a sleep(ms, value, fail) helper returning a promise: (a) time three sequential await sleep(100) vs Promise.all; (b) [1,2,3].forEach(async id => { await sleep(50); saved.push(id) }) and check saved.length immediately and 80 ms later; (c) call an async function that throws, without awaiting, and catch it later; (d) schedule Promise.reject(new Error('nobody caught me')) in a timer and observe Node's exit code; then add a process.on('unhandledRejection') handler, and in the browser a window.addEventListener('unhandledrejection') one.

P7. Combinators, timeouts and retries

Using tasks of 100 ms (success), 50 ms (failure) and 150 ms (success), run Promise.all, allSettled, any and race and print when and how each settles. Then implement withTimeout(fn, ms) using AbortSignal.timeout and a cancellable operation that clears its timer on abort, and retry(fn, attempts, baseMs) with exponential back-off and full jitter (Volume 1, chapter 09's P12). Test retry against a function that fails twice then succeeds.

P8. Fix search-as-you-type

Build a search box over a fake API (fetch to a local endpoint, or a function that resolves after a random 50–500 ms delay) and type "d", "do", "dos", "dosa" quickly. Show that the naive version can end on the wrong results. Fix it with (a) AbortController per request and (b) a latest-request ID guard, add a 200 ms debounce, and show loading and error states correctly (an aborted request must not show an error).

P9. Long tasks and yielding

Write a function that processes 2,000 orders (computing totals and grouping by kitchen, ~300 ms of CPU) on a page with a button that updates a counter on click. Click during processing and measure the delay between the click and the handler (performance.now() at the click's event.timeStamp vs handler start). Then chunk the work with await scheduler.yield() (falling back to new Promise(r => setTimeout(r))) every ~5 ms of work, and measure again. Finally move it to a Web Worker and compare.

P10. Generators and async iteration

Write an infinite ids() generator and a take(iterable, n) generator, and print [...take(ids(), 5)]. Make a Cart class iterable over its items with *[Symbol.iterator](). Then write an async generator over a paginated local API (3 pages of 50 orders with next cursors), consume it with for await, and stop after 70 orders; check in the server log that only two pages were requested.

P11. Proxy, WeakMap and binary data

(a) Write a Proxy that validates that paise is an integer, and test it. (b) Cache an expensive computation per DOM element in a WeakMap versus a Map; remove the elements, force garbage collection in DevTools, and compare retained memory. (c) Read the width and height from a PNG file's IHDR chunk in the browser with file.arrayBuffer() and a DataView (big-endian), as Volume 1, chapter 06's P8 did in Java. (d) structuredClone an object containing a Map, a Date and a cycle.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–15)

C1. A robust API client for the TiffinBox frontend

Write a small JavaScript module api.js used by every page: get, post, put with JSON bodies; a base URL and same-origin credentials; timeouts with AbortSignal.timeout combined with caller signals; retries with jittered back-off for idempotent requests only; parsing of errors into a typed error object (ApiError with status, code, message, requestId); idempotency keys for POSTs; IDs and money kept as strings or integers exactly as the API contract says (Volume 1, chapter 06's T13); and request deduplication (two identical GETs in flight share one fetch). Write unit tests with a fake fetch.

Combines: HTTP semantics, status codes and retries (Vol 1 ch 09); error handling and API design (ch 02); maps for in-flight deduplication (ch 03); probability of retries (ch 05); JSON number rules (ch 06); this volume's origins and cookies (ch 12), forms and encoding (ch 13) and all of this chapter's async material.

C2. An order-processing worker and UI that never freezes

Build a page that imports a CSV of 50,000 orders (chosen by the user), parses it, validates rows (dates, money in paise, kitchen IDs), aggregates totals per kitchen and per day, and shows progress and results, while the UI stays responsive (a typing test box must stay smooth). Do parsing and aggregation in a Web Worker with transferable buffers, stream the file with file.stream() and a TextDecoderStream, report progress messages, support cancel, and handle errors per row (report the first 100 with line numbers).

Combines: CSV and text processing (Vol 1 ch 01, 02); maps and aggregation (ch 03, 04); validation (ch 05); UTF-8 decoding, money and dates (ch 06); concurrency and message passing (ch 08); this volume's workers and event loop (ch 12) and this chapter's async iteration, typed arrays and structured clone.

C3. Port a Java utility to JavaScript and test them against each other

Take Volume 1's Java Money record (chapter 06's C2: integer minor units, currency, allocation by ratios, parsing, formatting) and port it to JavaScript using BigInt for amounts. Write property-based tests in both languages (jqwik in Java, fast-check in JavaScript) and a differential test: generate random operations, run them through both implementations (the Java side via a small CLI reading JSON lines on stdin), and compare outputs. Document every behavioural difference you find and fix them.

Combines: stdin/stdout CLIs and JSON lines (Vol 1 ch 01, 09); Java records and testing (ch 02); allocation algorithms (ch 04); property-based thinking (ch 05); integers, BigInt, rounding and parsing (ch 06); compilers and runtimes' different semantics (ch 10); this chapter's numbers, BigInt, Intl and classes.

What the chapter leaves out

Modules in depth: ESM, CommonJS and bundling

JavaScript has two module systems: ES modules (import/export, static structure, asynchronous loading, import.meta, top-level await, strict mode) and Node's older CommonJS (require, module.exports, synchronous, dynamic). Interop causes real pain: packages that ship only one format, require of an ESM package (now supported synchronously in recent Node for modules without top-level await), default-export mismatches, and the dual-package hazard (two copies of a library's state). Package exports maps define what's importable. Bundlers (chapter 30) resolve all of this at build time, tree-shake unused exports (which only works with static ESM imports), and split code with dynamic import(). Write ESM for new code.

Memory management and leaks in long-lived pages

Single-page apps stay open for hours, so leaks accumulate: listeners not removed (P2), timers and intervals not cleared, detached DOM trees referenced from JS, growing caches and logs in global arrays, closures capturing large objects, and observers (ResizeObserver, IntersectionObserver) not disconnected. Diagnose with DevTools' Memory panel: take a heap snapshot, perform an action several times (open/close a modal), take another, and compare (look for "Detached" nodes and growing object counts); the Performance panel's memory track shows sawtooth (healthy GC) versus a rising floor (leak). Use AbortController signals and framework teardown hooks systematically.

Security in JavaScript code itself

Beyond XSS sinks (chapter 12's T12): prototype pollution (merging untrusted JSON into objects with keys like __proto__ or constructor.prototype changes behaviour for every object; use Object.create(null) maps, Map, or libraries that block these keys, and validate input with schemas), eval/new Function/setTimeout with strings (never with user data; CSP can forbid them), ReDoS in client-side regexes (Volume 1, chapter 04's P11), supply-chain risk from npm dependencies (a compromised package runs in your origin: lock files, audits, minimal dependencies, Subresource Integrity for CDN scripts), and secrets in frontend bundles (anything shipped to the browser is public: API keys must be restricted or kept on the server).

Error handling and observability in the browser

Production JavaScript errors happen on devices you'll never see. Capture them: window.onerror / error events (with crossorigin on scripts from CDNs to get messages instead of "Script error."), unhandledrejection (P6), framework error boundaries (chapter 22), and report them with source maps (uploaded privately to the error tracker, not served publicly unless you're fine with that) so minified stack traces map back to your code, plus breadcrumbs (recent user actions, network calls) and release versions. Custom Error subclasses with cause (new ApiError('…', { cause: e })) preserve the chain. Chapter 32 builds the full pipeline.

Performance characteristics of JavaScript engines

V8, SpiderMonkey and JavaScriptCore JIT-compile hot code using hidden classes / shapes and inline caches, the same ideas as Volume 1, chapter 10's T9: objects created with the same properties in the same order share a shape and get fast property access; adding properties in different orders, delete, or mixing types in an array (integers, then a string) creates polymorphic or megamorphic sites and deoptimisations. Practical rules: initialise all fields in constructors in a consistent order, keep arrays monomorphic (all small integers, or all doubles, or all objects), avoid delete on hot objects (set to undefined or use a Map), and measure with the Performance panel rather than micro-optimising blindly. Large bundles also cost parse and compile time on low-end phones (chapter 27).

The language's evolution and TC39

JavaScript evolves yearly through TC39's staged process (stage 0 to 4; stage 4 ships in the next ECMAScript edition), with browsers often shipping features at stage 3. Recent and upcoming additions worth knowing: iterator helpers, Promise.withResolvers, Object.groupBy, Array.prototype.toSorted and friends, Set methods (union, intersection), Temporal, explicit resource management (using declarations with Symbol.dispose, like Java's try-with-resources), decorators, RegExp v flag, and import attributes (import data from './x.json' with { type: 'json' }). Check MDN and Baseline status before relying on them (chapter 12's gaps), and let TypeScript or a transpiler cover gaps where needed.

Senior exercises

S1. Diagnose a memory leak in a long-running dashboard

The kitchen-partner dashboard (open all day on a tablet in each kitchen) slows down and crashes after 6–8 hours. It polls new orders every 10 seconds, shows toasts, and opens order-detail modals. Lay out the investigation with DevTools (what to record, how to compare), the likely causes in this kind of app, and the fixes, plus how to stop regressions.

S2. Review an async-heavy pull request

A PR implements "reorder your last order": it fetches the last order, then in a forEach(async item => …) loop checks each item's availability with a request and adds it to the cart, catches errors with an empty catch {}, shows "Added!" immediately after the loop, computes the new cart total with items.reduce((s, i) => s + i.price * i.qty, 0) where price is a string from the API, and stores the cart with localStorage.setItem('cart', cart). Write the review, ranked by severity.

S3. Decide how much JavaScript to ship

TiffinBox's menu page ships 450 KB of compressed JavaScript (a framework, a component library, analytics, a date library, a chat widget). On a typical Indian mid-range phone, it takes about 2.5 s of main-thread time to parse, compile and run before the page is interactive. Write a plan to cut it below 100 KB for the first load, with the measurements you'd use, the specific techniques, and how you'd keep it there.

S4. Explain the event loop to Java backend engineers

Your Java backend colleagues will start writing Node.js services and frontend code. Prepare a 15-minute explanation of the JavaScript concurrency model in terms they know (threads, executors, CompletableFuture, virtual threads), with two live demos and three rules for writing correct async code.

S5. Write the team's JavaScript coding standard

Write a concise JavaScript coding standard for TiffinBox's frontend (and Node tooling): language rules (equality, declarations, modules, strictness), async rules, data and money rules, dates and Intl, error handling, security, and dependencies, each with its reason and the ESLint rule or tool that enforces it.