Fixing Loop Closures with Let
You'll learn how let solves the classic loop closure problem by creating a fresh binding for each iteration.
The Problem Recap
Remember the loop closure trap? When you use var in a loop, all closures share the same variable, so they all capture its final value. This happens because var is function-scoped — there's only one binding for the entire loop.
How Let Fixes It
When you use let (or const) in a for loop, JavaScript creates a new binding for each iteration. It's as if each trip through the loop gets its own private copy of the loop variable. Each closure then captures its own distinct binding, preserving the value from that specific iteration.
const callbacks = [];
for (let i = 0; i < 3; i++) {
callbacks.push(function() {
console.log(i);
});
}
callbacks[0](); // 0
callbacks[1](); // 1
callbacks[2](); // 2
Each iteration's i is isolated, so each function remembers the correct value.
Think of It Like This
With var, it's like everyone sharing one whiteboard — whoever writes last determines what everyone sees. With let, each iteration gets its own sticky note, and each function keeps the note from its iteration.
In Practice
const timers = [];
for (let i = 1; i <= 3; i++) {
timers.push(setTimeout(() => {
console.log(`Timer ${i}`);
}, i * 1000));
}
// Logs: Timer 1, Timer 2, Timer 3 (at correct intervals)
Each timeout closure captures its own i.
Key Takeaway: Block-scoped let creates a new binding per loop iteration, so each closure captures its own distinct value — automatically fixing the loop closure trap without extra IIFEs or workarounds.