JavaScript Closures Under the Hood: Scope, Lifetime, and Leaks
Closures are how JavaScript scope works, not a feature you opt into. Here is the mental model that finally made it click. A closure is the combination of a function and the lexical environment in which it was created. Every function in JavaScript closes over the variables in scope at the point of its definition. This is not a feature you switch on; it is the mechanism that makes scope work. Once I internalized that closures are always happening, a lot of confusing behavior stopped being confusing. Lexical Scope Determines Captured Variables Lexical scope means a function's accessible variables are determined by where the function is written in the source, not where it is called. A function defined inside another function has access to the outer function's parameters and locals. When the inner function outlives the outer function call, it carries a reference to the outer's variable environment, and that is the closure. function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); counter(); // 1 counter(); // 2 The count variable is not accessible from outside makeCounter, yet the returned function reads and mutates it.…