Interview Q&A · JavaScript · 12 questions in this topic

Iterators, Proxies & Metaprogramming — JavaScript Interview Q&A

All JavaScript topics

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

Example.jsjs
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

Example.jsjs
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

Example.jsjs
const guarded = new Proxy({}, {
  get: (t, k) => (k in t ? Reflect.get(t, k) : 42),
});

💡 Validation-and-virtualization are the flagship proxy uses.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits