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.

Left, before: the stack holds the frame of makeCounter() with a pointer to environment E1 {n = 0} in the heap, and the new closure λ1 points to E1. Right, after makeCounter returns: the frame is gone from the stack, global c1 points to closure λ1, λ1 still points to E1 {n = 0}, so E1 stays.
The frame of makeCounter is popped; its environment E1 lives on because the closure c1 points to it.

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.

LineEnvironment of the calln found inPrints
c1()E3, parent E1E1, n 0 → 11
c1()E4, parent E1E1, n 1 → 22
c2()E5, parent E2E2, n 0 → 11

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.

Left, for var i: closures λ0, λ1 and λ2 all point to the single environment E0 where i = 3; calling them prints 3, 3, 3. Right, for let i: λ0 points to E1 with i = 0, λ1 to E2 with i = 1, λ2 to E3 with i = 2; calling them prints 0, 1, 2.
var: one shared i, so 3, 3, 3. let: one i per iteration, so 0, 1, 2.

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 call base(4): environment E3 {h = 4} has parent E2 {w = 3}, whose parent is E1 {l = 2}, whose parent is the global E0 {vol, base}. The closure base, λ2, points to E2. Looking up l from E3 checks E3, then E2, then finds l = 2 in E1: 2 parent hops. The result is 2 times 3 times 4 = 24.
Each curried argument lives in its own environment; base(4) finds l two parent hops up.

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

LanguageWhat a closure captures
JavaScript, Scheme, PythonThe variable itself, through the environment. In Python, a nested function needs nonlocal n to assign to n.
JavaOnly 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.
HaskellEvery 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).

On the mind map

This page on the Recursion mind map · 15 pages in 4 branches · open it to see the whole map and test yourself in recall mode.