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

Scope & Closures — JavaScript Interview Q&A

All JavaScript topics

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

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

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

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

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