Inside JavaScript Closures: Scope Chain, outer Pointer, and Why Variables Survive
Every JavaScript module pattern, counter, event handler, and useMemo callback rests on closures, so the ability to model them as outer-pointer chains turns a memorized definition into a debuggable mechanism. It also makes the cost explicit: keeping a closure reference alive keeps every captured variable in heap memory until the reference is broken.
JavaScript closures are a natural result of lexical scoping and the scope chain, not a standalone syntax feature. Each execution context carries an outer pointer determined at function definition time; it points to the enclosing scope where the function is written. During variable lookup, the engine searches the current AO first, then follows outer to the upper scope until reaching GO, or throws is not defined. This chain of pointers is the scope chain.
A closure appears only when an inner function is carried out of its outer function: returned, assigned to a global variable, or passed as a callback. Without that, an inner function called only inside the outer function produces no closure, and the outer execution context pops and reclaims variables as usual. When a carried-out function still depends on outer variables, V8 preserves exactly the variables the inner function uses instead of destroying the whole AO, and that retained variable set is the closure.
The mechanics give closures two practical benefits: they let variables outlive their outer function, and they can encapsulate private state that only exposed methods can modify. The known catch is memory: as long as a closure reference is held, its captured variables stay in heap memory. Setting an unused closure reference to null breaks the reference chain and lets GC reclaim that data.
Closure behavior is not a special feature of syntax; it falls out of lexical binding plus a GC decision, and the article's sharpest point is that V8 keeps only the referenced outer variables, so the memory cost is narrower than 'the whole outer scope'.
The assertion that the outer pointer is fixed at definition time explains why a function sees the scope where it was written, not where it was called, which is a frequent source of confusion in event handlers and async callbacks.
The explicit condition that a nested function must escape its parent before a closure forms is a practical test for memory planning: defining nested functions costs nothing, returning them costs memory.
The standard cleanup of add = null only works when no other reference to the returned function exists; in real code with event listeners or caches, breaking the reference chain is not always that simple.
Using the outer pointer to explain closures is the right approach — you can see at a glance where variables are being looked up. The moment the setTimeout loop example appears, the beginner confusion basically dissipates.