Scope, Closures, and Objects: How JavaScript Keeps Variables Alive After Functions Return
Misreading these rules produces real bugs: shared loop variables, unexpected value binding, and memory bloat from retained closures. This breakdown gives developers the mental model to predict variable lifetime and lookup order in any JavaScript codebase.
The article builds a mental model for three connected JavaScript mechanics. Scope defines where variables are visible, and the rules are one-way: inner functions can see outer variables, but not vice versa. Lexical scope matters more than call location, which is why a function defined globally still reads the global variable even when invoked inside another function. Closures then explain what happens when a function outlives its outer function: referenced variables are retained in a persistent set, enabling private state, counters, and the classic `var` in a loop problem that `let` solves by creating per-iteration bindings. Finally, objects and the prototype chain determine how variables and methods are stored and shared, along with the wrapper class behavior that prevents primitive values from holding properties. The article ties these together with the opening puzzle: `getAge()` returns `18` because lexical scope grants access, closures keep the variable alive, and the structure that carries it is ultimately object-like.
The article explicitly separates the call stack from the scope chain, correcting a common conflation that muddles how variable lookup and function return are handled.
Treating a closure as the retained variable set, rather than just the function, makes the memory implications and the mechanism behind private state clearer.