beginner
scope
functions
· 8 min

What is a closure and when does it actually matter?

TL;DR
A closure is a function bundled with a reference to the lexical environment where it was defined. It matters whenever a function outlives the scope that created it — callbacks, factories, module patterns, memoization.

The textbook definition

Every function in JavaScript captures the variable environment active at the moment of its creation. When the function is later invoked — possibly long after the outer function returned — it still has access to those variables by reference, not by value.

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const c = makeCounter();
c(); // 1
c(); // 2
Each makeCounter() call creates a fresh, private `count`.

Where closures actually bite you

  • Stale closures in React hooks (capturing an old state value).
  • Accidental memory retention when long-lived callbacks hold large objects.
  • Loop-variable bugs with `var` (fixed by `let` giving per-iteration scope).

Visualize closure scope

Watch how two counters keep independent private state.

Interactive
counter A
0
This instance holds its own private count — incrementing here does not affect the other counter.
counter B
0
This instance holds its own private count — incrementing here does not affect the other counter.