Closures: The Real Mental Model

A closure is created when a function retains access to variables from its lexical environment even after the outer function has finished executing. The important concept is not merely 'a function inside another function'; it is that the inner function retains access to the relevant lexical bindings.

Closures are used for private state, factories, memoization, callbacks, module patterns, and asynchronous code.

Private State with a Closure
function createCounter() {
  let count = 0;

  return function increment() {
    count += 1;
    return count;
  };
}

const counter = createCounter();
console.log(counter());
console.log(counter());
💡 createCounter returns after creating the inner function, but the returned function still has access to count. The binding remains reachable through the closure.
Key Takeaways
  • Closures preserve access to lexical bindings.
  • Closures are useful for encapsulation and state.
  • A closure retains reachable bindings, not necessarily every variable from the entire outer scope.
Knowledge Check

Why does `count` remain available after `createCounter()` returns?