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.
The 60-second answer
Section titled “The 60-second answer”“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.”
Scope in one table
Section titled “Scope in one table”| 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.
Closures in practice
Section titled “Closures in practice”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.
The module pattern
Section titled “The module pattern”Before ES modules, closures were the only way to get private state:
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.
The loop variable pitfall
Section titled “The loop variable pitfall”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 iterationlet 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.
Memory implications
Section titled “Memory implications”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
useCallbackexists.
Rules of thumb:
- Capture the smallest value you need (
const id = user.id, notuser). - Remove listeners on unmount;
AbortControllermakes that clean. - Prefer module-level functions when no state is captured.
- Do not micro-optimise; worry about long-lived closures holding large objects.
Follow-up questions
Section titled “Follow-up questions”- Why does
letin aforloop create a new binding whenvardoes not? - What is the temporal dead zone and what problem does it solve?
- How would you implement
memoizewith a closure, and what is its memory risk? - Do closures capture variables or values?
- How do React hooks depend on closures, and what breaks when you lie about dependencies?
Common traps
Section titled “Common traps”- “A closure copies the value.” It captures the binding. If the variable changes, the closure sees the new value.
- “
letis block-scoped, so closures over it break in loops.” The opposite:letfixes 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;
thisis 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.