The idea: a function that remembers where it was made
In P1, makeCounter() declares a local variable n and returns a small arrow function that adds 1 to n. The arrow function uses n, but n belongs to makeCounter, and makeCounter has already returned when the arrow function runs. It still works, because a function value in JavaScript is a closure: the code plus a pointer to the environment (the set of variables) where the function was created. The closure "closes over" n.
On the canvas, the heap panel shows each environment as a white box E<k> with its variables, and each closure as a yellow box λ<k>. A blue arrow goes from a closure to the environment it captured. A purple arrow goes from an environment to its parent, the environment around it. To find a name, JavaScript looks in the current environment, then follows parent arrows until it finds it.
The environment outlives the frame
In a language without closures, like C, a local variable lives in the stack frame and dies when the function returns. That is not possible here: the closure still needs n. So each call keeps its variables in an environment in the heap. The stack frame only points to it. When makeCounter() returns, the frame is popped and E1 stays (Demo 1).
An environment is freed only when nothing can reach it: no variable, no frame and no live closure. The page runs a tiny garbage collector after each line. It marks everything reachable from the global environment E0 and from the frames, and frees the rest (grey boxes). The environment made for a call like c1() is freed right after it returns, because no closure was created inside it. See mark-sweep vs reference counting for how real collectors do this.
Two counters are independent
Every call of makeCounter makes a new environment. c1 points to E1 and c2 to E2, and each has its own n. So c1(), c1(), c2() prints 1, 2, 1 (Demo 2). Each call of c1 makes a fresh, empty environment whose parent is E1: the environment c1 captured, not the global one where c1 was called. The lookup of n goes 1 parent hop, from the call's environment to E1, and n = n + 1 changes n inside E1 itself. After the run, E1 holds n = 2 and E2 holds n = 1. This is the usual way to make private state in JavaScript: nothing outside c1 can read or change its n.
| Line | Environment of the call | n found in | Prints |
|---|---|---|---|
c1() | E3, parent E1 | E1, n 0 → 1 | 1 |
c1() | E4, parent E1 | E1, n 1 → 2 | 2 |
c2() | E5, parent E2 | E2, n 0 → 1 | 1 |
The loop variable capture bug
P2 makes three closures in a loop, and each returns i. With var i, the loop has one i, in the enclosing environment (here the global E0). All three closures point to E0. They run after the loop has ended, when i is 3, so they print 3, 3, 3 (Demo 3). A closure captures the variable, not the value it had at the time.
P3 is the same loop with let i. Now each iteration gets its own environment: E1 {i = 0}, E2 {i = 1}, E3 {i = 2}. Each closure points to its own one and prints 0, 1, 2 (Demo 4). Before let existed (ES2015), the fix was to call a function inside the loop, which made a new environment per iteration by hand.
Currying and partial application
Currying turns a function of several arguments into a chain of functions of one argument each. add = a => b => a + b takes a and returns a closure that waits for b. So add(2)(3) is two calls: add(2) makes E1 {a = 2} and returns λ1 (which captured E1), then λ1(3) makes E2 {b = 3}, finds a one hop up and returns 5. Afterwards nothing points to λ1, E1 or E2, so all three are freed (Demo 5).
Partial application fixes some arguments now and leaves the rest for later. add2 = add(2) keeps the closure: add2 points to E3 {a = 2}, which now stays alive. add2(10) returns 12. With currying, partial application is just "call with fewer arguments". Without it, JavaScript has f.bind(null, 2), and Python has functools.partial(f, 2).
With three levels, vol = l => w => h => l * w * h and base = vol(2)(3), base keeps a chain of environments: E2 {w = 3} → E1 {l = 2} → E0. λ1, the middle closure, is freed, but E1 is kept, because E2's parent pointer still reaches it. base(4) makes E3 {h = 4}; the lookup of l goes E3 → E2 → E1, 2 parent hops, and the result is 2 · 3 · 4 = 24. base(5) gives 30 (Demo 6).
The parent chain is the same idea as the static chain in static vs dynamic scoping: a name is looked up where the function is written, not where it is called. Closures just keep that chain alive after the calls have returned.
Closures in other languages
| Language | What a closure captures |
|---|---|
| JavaScript, Scheme, Python | The variable itself, through the environment. In Python, a nested function needs nonlocal n to assign to n. |
| Java | Only effectively final local variables, so it copies the value. A counter needs a field or an array. |
| C++ | What the capture list says: [n] copies, [&n] refers, and a reference to a returned function's local is dangling. |
| Haskell | Every function is curried: add 2 3 is (add 2) 3. |
See also map, filter and reduce (closures are the functions you pass to them), recursion to an explicit stack (what a frame holds), Java lambdas and invokedynamic (how the JVM turns a lambda into an object with captured values) and parameter passing.
See also Hindley-Milner type inference, which works out curried types such as ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b for compose.
What the page leaves out
The page runs five tiny programs with numbers only. It leaves out how engines avoid heap environments when no closure escapes (escape analysis keeps such variables in registers or the stack), how they share one environment object between several closures, this and arguments, hoisting and the temporal dead zone of let, the exact copy step of a let loop, closures in asynchronous callbacks, and when a real garbage collector runs (here it runs after every line).