Frontend · interactive
Closures
A function remembers the variables that were in scope where it was created, not copies of their values. That's a closure. It explains the classic loop bug, and it's how JavaScript does private state.
for (var i = 0; i < 3; i++) {
setTimeout(() => log(i), 0);
}Scopes kept alive
function scope (one for the whole loop)
i = 3
↖ callback 1↖ callback 2↖ callback 3
output: 3 3 3
var creates one i for the whole function. All three callbacks close over that same variable, and by the time they run the loop has left it at 3.
Example
Step 2 of 4 · read left to right
In production
Tools and technologies
Closures are everywhere in JavaScript: callbacks, hooks, modules.
Not tied to one language — use these names when you search docs or design a system.