The Loop Closure Trap
In this lesson, you'll learn why using var in loops can cause all closures to capture the same final value, leading to unexpected behavior.
The Problem with var in Loops
When you create closures inside a loop using var, all those closures share the same variable. Since var is function-scoped (not block-scoped), there's only one variable for the entire loop. By the time your closures run, the loop has finished, and they all see the final value.
A Classic Example
var functions = [];
for (var i = 0; i < 3; i++) {
functions.push(function() {
console.log(i);
});
}
functions[0](); // 3 (not 0!)
functions[1](); // 3 (not 1!)
functions[2](); // 3 (not 2!)
All three functions print 3 because they all close over the same i variable, which equals 3 after the loop completes.
The Solution: Block Scope with let
Using let creates a new variable for each iteration:
var functions = [];
for (let i = 0; i < 3; i++) {
functions.push(function() {
console.log(i);
});
}
functions[0](); // 0 ✓
functions[1](); // 1 ✓
functions[2](); // 2 ✓
Each closure now captures its own separate i variable from that specific iteration.
The Mental Model
Think of var as having one mailbox for the whole apartment building (the loop), while let gives each apartment (iteration) its own mailbox. When closures check their mail later, var users all find the same final message, but let users find their individual messages.
Key Takeaway: Use let (not var) in loops when creating closures, or every closure will capture the same final loop value instead of its own iteration's value.