Closures
Call a function, and when it returns, the variables it created are usually gone. Here is one whose variable survives anyway:
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2
makeCounter has already returned by the time next() runs, yet count keeps its value and the returned function can still update it. A function bundled with the scope it was defined in is a closure. It holds the variables themselves, not a copy of their values.
Each call to makeCounter creates a fresh count. Two counters do not share
state:
const a = makeCounter();
const b = makeCounter();
a(); // 1
a(); // 2
b(); // 1
Closures are how you get private state, factory functions, and callbacks that
remember where they came from. A loop variable captured by a closure is the
classic trap: var gives every callback the same binding, while let gives
each iteration its own.
You are about to answer a short quiz on closures.