Interview Q&A · JavaScript · 12 questions in this topic
Iterators, Proxies & Metaprogramming — JavaScript Interview Q&A
Beyond everyday syntax — iteration protocols, proxies, reflection and descriptors. Part of Modules & Metaprogramming · 204 questions in the JavaScript bank.
How do iteration protocols work (iterable vs iterator)?
Answer
Iterables expose [Symbol.iterator]() returning iterators; iterators expose next() → {value, done}. for...of, spread and destructuring consume iterables. Custom iterables (ranges, paginated streams) implement the method once and gain all consumers.
One-method-unlocks-everything is the protocol payoff.
Example
const range = { *[Symbol.iterator]() { yield 1; yield 2; yield 3; }, }; [...range]; // [1, 2, 3] (spread consumes it)
What is the difference between `for...of` and `for...in`?
Answer
for...of iterates iterable values (arrays, strings, Maps, custom) — values, with break/await support. for...in enumerates string keys including inherited (objects' keys, plus array indices as strings — usually wrong for arrays).
of-for-values, in-for-keys is the selection rule.
Example
for (const v of [10, 20]) {} // values: 10, 20 for (const k in { a: 1 }) {} // keys: 'a'
How do `Proxy` and `Reflect` work (traps, invariants)?
Answer
Proxy wraps targets intercepting get/set/has/apply via traps (validation, logging, virtual props, deprecation shims); Reflect mirrors default behaviors for forwarding inside traps. Invariants (non-configurable/non-writable honesty) keep traps truthful — violating throws.
Intercept-with-Reflect-forward is the trap pattern.
Example
const guarded = new Proxy({}, { get: (t, k) => (k in t ? Reflect.get(t, k) : 42), });
💡 Validation-and-virtualization are the flagship proxy uses.
What is `Reflect` for (vs direct operators)?
Answer
Reflect mirrors operators as functions (get/set/has/deleteProperty/apply/construct) — composable, first-class, proxy-trap-mirroring, with boolean returns (Reflect.set success flag vs throwing assignment). Proxies forward via Reflect to preserve default semantics.
Functions-where-operators-were is the Reflect elevator pitch.
Example
// Reflect.get(target, key) === target[key] (forwardable form)How do `Map`, `Set`, `WeakMap` and `WeakSet` compare to objects?
Answer
Map: any-key dictionaries with size/iteration/insertion order (objects: string/symbol keys only). Set: unique values with O(1) membership. WeakMap/WeakSet: object-keyed, weakly held (GC-friendly caches/metadata, non-iterable).
Keys-beyond-strings → Map; membership → Set; GC-sensitive metadata → WeakMap.
Key points
- 1Map — arbitrary keys, ordered, sized.
- 2Set — unique membership.
- 3Weak* — GC-friendly, non-enumerable.
Example
const cache = new WeakMap(); // entries vanish with keys (GC)
💡 Weak-allows-GC is the memory story.
How do you pick: object vs Map vs WeakMap?
Answer
Fixed-shape records → objects (literal ergonomics, JSON). Dynamic/arbitrary keys + iteration → Map. Private-per-instance/external metadata needing GC → WeakMap. JSON serialization needs plain objects/Maps-converted.
Shape-fixed → object; keys-dynamic → Map; GC-coupled → WeakMap.
Example
// JSON needs plain data: Object.fromEntries(map)How do you implement observable state (mini reactivity)?
Answer
Proxy set-trap notifying subscribers (dependency tracking via effect stacks for computed granularity) — the Vue-3 core shape. Effects re-run on dependency change; cleanup unsubscribes. Scheduler batches notifications (microtask) to avoid redundant renders.
Trap-notify-schedule is the reactivity skeleton.
Example
// const state = observable({ n: 1 }); // effect(() => render(state.n)); // re-runs on set
💡 Dependency-tracking-plus-batched-notify is the framework insight.
What are well-known symbols (`iterator`, `toPrimitive`, `species`)?
Answer
Language hooks: Symbol.iterator (iteration), Symbol.toPrimitive (conversion), Symbol.hasInstance (instanceof), Symbol.species (derived constructors in methods like map), Symbol.dispose (explicit resource management). Customizing them adapts built-in protocols.
Protocol-hooks-not-magic is the framing.
Example
class MyArr extends Array { static get [Symbol.species]() { return Array; } // map returns plain Array }
What is explicit resource management (`using`, Symbol.dispose)?
Answer
using declarations auto-dispose block-scoped resources (files, locks) at scope exit — deterministic cleanup without try/finally pyramids. Objects implement [Symbol.dispose]/asyncDispose; DisposableStack composes multiple.
Scope-exit-cleanup is the RAII-arrives-in-JS story.
Example
// { // using file = openFile(); // disposed at block end // }
💡 RAII-for-JS is the one-line significance.
How do decorators (`@`) work (TC39)?
Answer
Decorators wrap classes/members at definition (logged, bound, validated, memoized) via functions receiving target/context and returning replacements. Method decorators wrap descriptors; field decorators transform initialization; ordering (bottom-up application) matters.
Definition-time-transformation is the decorator model.
Example
// @logged // class Api {} // class definition transformed
💡 Babel/TS-experimental vs standard is the ecosystem caveat.
How does `structuredClone` compare to JSON round-trip and spread?
Answer
structuredClone deep-clones structured data (Dates, Maps, Sets, cycles, typed arrays) — not functions/DOM. Spread is shallow. JSON loses types (Dates→strings, drops undefined/functions) and chokes on cycles/BigInt.
structuredClone-default for true copies is the modern rule.
Example
const copy = structuredClone({ d: new Date(), m: new Map() });
What is the difference between `null` and `undefined` in JSON and APIs?
Answer
JSON has null, no undefined (undefined fields are dropped on stringify). APIs: null means explicitly-empty, absent means untouched — PATCH semantics depend on the distinction. ?? preserves null-vs-absent carefully at boundaries.
Dropped-undefined is the serialization edge to know.
Example
JSON.stringify({ a: undefined, b: null }); // '{"b":null}' (a dropped!)
Recommended resourcesAffiliate links · may earn us a commission