Solving Loop Closures with let
What you'll learn: How using let in loop declarations automatically fixes the loop closure problem by creating a new binding for each iteration.
The Automatic Fix
In the previous lesson, you saw how closures inside loops capture the same variable, leading to unexpected behavior. The simplest modern solution? Use let instead of var in your loop declaration.
When you declare a loop variable with let, JavaScript creates a new, separate binding for each iteration. It's like giving each iteration its own private locker instead of everyone sharing one locker that keeps getting updated.
How It Works
const functions = [];
for (let i = 0; i < 3; i++) {
functions.push(function() {
console.log(i);
});
}
functions[0](); // 0
functions[1](); // 1
functions[2](); // 2
Behind the scenes, let i creates a fresh i variable for each loop cycle. Each closure captures its own i, not a shared one.
The Contrast with var
const functions = [];
for (var i = 0; i < 3; i++) {
functions.push(function() {
console.log(i);
});
}
functions[0](); // 3
functions[1](); // 3
functions[2](); // 3
With var, there's only one i that all closures reference, and it ends up at 3 after the loop completes.
Why This Matters
Block-scoped let was designed specifically to handle this common closure pitfall. Each iteration gets its own lexical environment, so closures naturally capture the value you expect.
Key Takeaway: Using let in loop declarations creates a new binding per iteration, giving each closure its own independent copy of the loop variable—no IIFE or workarounds needed.