Skip to content

Closures and Scope

A closure is a function together with the scope it was created in. That is the whole idea, and it explains most of the “weird” JavaScript behaviour interviewers ask about: private state without classes, handlers that remember the wrong value, and memory that never gets freed.

“JavaScript uses lexical scope: a function can see variables declared where it was written, not where it is called. When a function outlives its enclosing function, the engine keeps the environment alive, and we call that function a closure. Closures give us private state — the module pattern, once, memoisation, hooks — but they also keep anything they reference from being garbage collected. The classic bug is a var loop variable, which has one binding shared by every callback; let creates a fresh binding per iteration and fixes it.”

Construct Scope Hoisting
var Function (or global) Hoisted, initialised to undefined
let / const Block Hoisted but in the temporal dead zone
Function declaration Enclosing function/block Fully hoisted, callable before its line
Function expression / arrow Wherever it is assigned Not callable before assignment
class Block In the TDZ until evaluated

The temporal dead zone is why console.log(x); let x = 1; throws rather than printing undefined. It is a feature: it turns use-before-define into an error.

counter.js
function makeCounter(start = 0) {
let value = start; // captured by the returned functions
return {
increment: () => ++value,
decrement: () => --value,
current: () => value,
};
}
const counter = makeCounter(10);
counter.increment();
counter.current(); // 11
// There is no way to reach `value` from outside except through the closures.

Each call creates a new environment. Two counters do not share value, which is the difference between a closure and a global. The same trick backs once(fn), which caches a result after the first call, and memoize, which keeps a cache object alive for the lifetime of the returned function — a useful example and a memory risk in the same answer.

Before ES modules, closures were the only way to get private state:

module-pattern.js
const cart = (() => {
const items = []; // private
return { add(i) { items.push(i); }, total: () => items.reduce((s, i) => s + i.price, 0) };
})();

Modern code should use ES modules: real file-level privacy and static analysis. The pattern still appears in bundler output and wherever you need a fresh instance per call.

loop-var.js
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3, 3, 3 — one shared binding, already incremented to 3
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0, 1, 2 — a new binding per iteration

let in a for head is special-cased by the specification: at the end of each iteration the current binding is copied into a fresh one. That is why closures created inside the body capture the value at that iteration. The pre-let fix was an IIFE wrapping the body, which forces a new scope per iteration; you still see it in older codebases and it is worth recognising.

A closure keeps its referenced environment alive. Engines may optimise per variable, but you cannot rely on it.

  • A handler closing over a large array keeps that array alive while the handler is attached.
  • A closure referencing a DOM node keeps the node alive after removal — the classic detached-DOM leak.
  • Functions created inside a render create a new closure per render, which is why referential equality checks fail and useCallback exists.

Rules of thumb:

  1. Capture the smallest value you need (const id = user.id, not user).
  2. Remove listeners on unmount; AbortController makes that clean.
  3. Prefer module-level functions when no state is captured.
  4. Do not micro-optimise; worry about long-lived closures holding large objects.
  1. Why does let in a for loop create a new binding when var does not?
  2. What is the temporal dead zone and what problem does it solve?
  3. How would you implement memoize with a closure, and what is its memory risk?
  4. Do closures capture variables or values?
  5. How do React hooks depend on closures, and what breaks when you lie about dependencies?
  • “A closure copies the value.” It captures the binding. If the variable changes, the closure sees the new value.
  • “let is block-scoped, so closures over it break in loops.” The opposite: let fixes the bug.
  • “Closures are a leak.” They are a feature; the leak is holding something longer than needed.
  • Confusing scope with execution context. Scope is lexical and static; this is dynamic.
  • Assuming garbage collection is immediate. The environment is collected when nothing references it, which may be much later — or never, during the page’s lifetime.