The Loop Variable Capture Problem
You'll learn why using var in loops causes every closure to reference the same variable, leading to unexpected behavior.
The Core Issue
When you create closures inside a loop using var, all those closures share a reference to the same variable. This happens because var is function-scoped (or globally scoped), not block-scoped. By the time any closure executes, the loop has finished, and the variable holds its final value.
Here's the classic example:
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() {
return i;
});
}
console.log(funcs[0]()); // 3 (not 0!)
console.log(funcs[1]()); // 3 (not 1!)
console.log(funcs[2]()); // 3 (not 2!)
All three functions return 3 because they all captured a reference to the same i variable. When the loop finished, i was 3, so that's what every closure sees.
Why This Happens
With var, there's only one i variable for the entire loop. Each function created in the loop captures that same variable. The closures don't capture the value at each iteration—they capture the variable itself.
Think of it like giving three friends the same sticky note with a number on it. If you change the number before they read it, they all see the final number, not the number that was there when you handed them the note.
Key Takeaway: With var in loops, all closures share the same variable reference, so they all see its final value instead of the value at each iteration.