Interview Q&A · JavaScript · 10 questions in this topic
Scope & Closures — JavaScript Interview Q&A
Lexical scope, the scope chain, and closures — private state and the classic loop bug. Part of Functions & Closures · 204 questions in the JavaScript bank.
What is a closure?
Answer
A closure is a function bundled with its lexical environment — it remembers outer variables after the outer function returns. Every function in JavaScript closes over its birth scope; the mechanism powers private state, factories, callbacks and modules.
Functions carry backpacks of their birth scope — that image is the whole concept.
Example
function counter() { let n = 0; // private: only the closure sees it return () => ++n; } const c = counter(); c(); c(); // 1, 2 (n survives between calls)
💡 Function-plus-birth-scope is the definition; private-state is the flagship use.
How do closures create private state (module pattern)?
Answer
Outer function scope holds state; returned methods close over it — no external access except through the API. Pre-class privacy, still the cleanest factory privacy (per-instance state without # syntax or WeakMaps).
Revealing-module (return {public...}) documents the interface explicitly.
Example
function bank(balance) { return { deposit: (x) => (balance += x), get: () => balance, // balance unreachable otherwise }; }
Why does `var` in a loop break async callbacks (the classic bug)?
Answer
var is function-scoped: one shared binding across iterations, so all callbacks read the final value. let is block-scoped per iteration — each callback closes its own copy. IIFE-per-iteration was the pre-let fix.
Shared-binding vs per-iteration-binding is the entire bug and fix.
Example
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3 (shared!) for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2 (per-iteration)
What is the scope chain? How is variable lookup resolved?
Answer
Each function links to its lexical parent scope, forming a chain to global: lookup walks outward to the first binding found (shadowing inner wins). The chain is fixed at definition (lexical), not call site — dynamic scope does not exist in JS.
Scope is where-written, not where-called — the lexical rule.
Example
const x = 'global'; function outer() { const x = 'outer'; function inner() { return x; } // 'outer': definition-site chain return inner(); }
💡 Definition-site-not-call-site is the lexical scoping mantra.
What is the difference between function scope and block scope?
Answer
Function scope (var, function) spans the whole function regardless of braces. Block scope (let, const, class) lives within {} — ifs, loops, bare blocks. Blocks without functions now scope correctly, which is why let/const loops behave and var loops surprise.
Braces-are-boundaries is the modern rule; var predates it.
Example
if (true) { var a = 1; // escapes to function/global! let b = 2; // stays in the block } // console.log(a); // 1 (leaked) // console.log(b); // ReferenceError
Do closures cause memory leaks?
Answer
Closures retain everything reachable from their scope — accidentally kept big objects (DOM subtrees, caches) live as long as the closure. Detached-DOM-plus-handler is the classic leak: removed elements retained by closures. Fix by nulling references, removing listeners, and scoping closures narrowly.
Retention-by-reachability is the GC rule; closures extend reach.
Key points
- 1Retain — closed-over objects live with the closure.
- 2Leak — detached DOM, forgotten timers/listeners.
- 3Fix — narrow scope, cleanup, nulling.
Example
// leak shape: handler closes over huge data, never removed // element.remove(); // DOM gone, closure still holds it
💡 Reachability-not-visibility governs GC is the principle.
How do you implement private state: closures vs #fields vs WeakMap?
Answer
Closures: per-instance privacy via factories, methods re-created per instance (memory cost). #fields: class-native, truly private, prototype-shared methods — the modern default. WeakMap: external privacy store keyed by instance (GC-friendly, pre-# pattern).
Default #fields; closures for factory APIs; WeakMap for legacy/external attachment.
Example
class A { #x = 1; // truly private field get() { return this.#x; } } // a.#x // SyntaxError from outside
💡 One mechanism per era is the history that justifies the modern default.
What is the module pattern (pre-ES-modules)?
Answer
IIFE returning a public API object while hiding internals in closure scope — privacy, no globals, explicit interface. Revealing variant names privates plainly and exposes mappings. ES modules (import/export) replaced it with language-level structure plus static analysis.
History question with a surviving shape: narrow factory privacy still uses it.
Example
const mod = (function () { let n = 0; return { inc: () => ++n, get: () => n }; })();
How does garbage collection interact with closures and timers?
Answer
GC frees unreachable objects (mark-and-sweep); live timers/listeners/promises keep their closures (and everything reachable) alive. Uncleared intervals and unremoved listeners are the leak vectors — cleanup (clearInterval, removeEventListener, AbortController) releases them.
Every setInterval wants a clearInterval; every listener a removal path.
Example
const id = setInterval(tick, 1000); // ... later: clearInterval(id); // releases closure + reachables
💡 Timers-and-listeners-are-roots is the leak mental model.
What is lexical (`static`) scoping in one sentence plus example?
Answer
A function's variable meanings are fixed where it is written, not where it runs. Inner sees outer-at-definition; call location never changes resolution.
One rule, total predictability — the alternative (dynamic scope) would make every call site a meaning change.
Example
const v = 'G'; function show() { return v; } function run() { const v = 'L'; return show(); } run(); // 'G': definition site wins
Recommended resourcesAffiliate links · may earn us a commission