Sub topic 12
The Classic Loop Closure Bug
This chapter assumes you already know how closures capture their surrounding scope, how var differs from let in where a name is visible, and how var hoisting works. All of those were covered in earlier chapters. Here they combine into the most famous scope bug in JavaScript: a loop that creates functions, where every function ends up seeing the same value.
The Bug in Its Natural Habitat
The bug usually shows up when a loop schedules work for later. That work might be a timer, an event handler, or a promise callback. Here is the timer version:
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log("timer", i);
}, 0);
}
// timer 3
// timer 3
// timer 3Most people expect 0, 1, 2. They get 3 three times. The timers are not at fault. The same thing happens with no asynchronous code at all, if you store the functions and call them after the loop ends:
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(f => f())); // [3, 3, 3]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(f => f())); // [0, 1, 2]Changing var to let fixes it. To see why, you need to look at how many bindings each loop creates.
Why var Produces One Shared Binding
A binding is the storage slot that a name refers to. A closure does not copy a variable's value when the function is created. It keeps a reference to the scope that holds the binding, and it reads the binding's current value each time the function runs.
var is function-scoped. It ignores the braces of the loop. The var i in the loop header is hoisted to the enclosing function or script. That means the code above behaves as if it were written like this:
var i;
const fns = [];
for (i = 0; i < 3; i++) {
fns.push(() => i);
}
// All three arrows close over the same outer i.
console.log(i); // 3
console.log(fns.map(f => f())); // [3, 3, 3]There is exactly one i. The loop increments it to 0, 1, 2, and finally 3, which is the value that fails the i < 3 test and stops the loop. None of the closures run until later. When they do run, they all look up the same binding and find 3.
The bug, then, comes from scope and timing together. The functions are created during the loop and called after it, and every one of them refers to a single variable that has already moved on.
Why let Creates a Fresh Binding per Iteration
let in a for loop header does more than make i block-scoped. The language specification requires the engine to create a new lexical environment for each iteration and to copy the current value of the loop variable into it. The steps are:
- Create an environment for the loop header and run the initializer (
let j = 0). - Before the first iteration, copy
jinto a fresh per-iteration environment. - Run the test, then the body. Closures made in the body capture this iteration's environment.
- Copy the current value of
jinto a new environment for the next iteration. - Run the increment (
j++) on the new copy, then repeat from the test.
The increment always runs against the next iteration's binding. Because of that, the binding a closure captured in iteration 0 still holds 0 after the loop finishes.
Closures Still Capture Variables, Not Values
The per-iteration copy can mislead you into thinking that let makes closures capture values. It does not. Each closure still references a live binding. The binding just belongs to a single iteration. If you change the variable inside the body, the closure sees the change:
const fns = [];
for (let i = 0; i < 3; i++) {
fns.push(() => i);
i++; // mutates this iteration's binding
}
console.log(fns.map(f => f())); // [1, 3]Here is the trace. In iteration 1, the binding starts at 0. The closure is pushed, then i++ changes that same binding to 1. The value 1 is copied into iteration 2's binding, and the header's i++ makes it 2. The body pushes a closure and changes the binding to 3. The next copy is incremented to 4 and fails the test. The first closure reads 1 and the second reads 3.
Fixes and When to Use Each
| Fix | How it works | When to use it |
|---|---|---|
| `let` in the loop header | Per-iteration binding created by the engine | Default choice in modern code |
| `for...of` / `for...in` with `const` or `let` | Each iteration gets a new binding | Iterating arrays, strings, maps, or object keys |
| `array.forEach(i => ...)` | Each callback call has its own parameter scope | Functional style over arrays |
| IIFE wrapping the body | A new function scope per iteration captures a parameter | Legacy ES5 code that cannot use `let` |
| Extra argument to `setTimeout` or `.bind` | The value is passed in at creation time, not looked up later | Timers and handlers in old code |
The pre-ES2015 fix creates a new function scope by hand on every pass:
var fns = [];
for (var i = 0; i < 3; i++) {
(function (captured) {
fns.push(function () {
return captured;
});
})(i);
}
console.log(fns.map(function (f) { return f(); })); // [0, 1, 2]Each call to the immediately invoked function expression (IIFE) gets its own captured parameter, which holds a copy of i at that moment. setTimeout can also pass arguments straight through:
for (var i = 0; i < 3; i++) {
setTimeout(n => console.log("arg", n), 0, i);
}
// arg 0
// arg 1
// arg 2Edge Cases and Gotchas
let Declared Outside the Loop Does Not Help
The per-iteration copy applies only to bindings declared in the loop header. If you declare the variable before the loop, there is again one binding:
const fns = [];
let k;
for (k = 0; k < 3; k++) {
fns.push(() => k);
}
console.log(fns.map(f => f())); // [3, 3, 3]while and do...while Loops Have No Header Binding
A while loop has no declaration slot in its header, so the engine has nothing to copy. To get a fresh binding per pass, declare one inside the body. The body is a block, and a block creates a new environment each time it runs:
const fns = [];
let n = 0;
while (n < 3) {
const current = n; // new binding every pass through the block
fns.push(() => current);
n++;
}
console.log(fns.map(f => f())); // [0, 1, 2]const Works in for...of but Not in a Classic for
for (const x of list) is fine, because each iteration creates and initializes a brand-new binding. In a classic for loop, the increment step assigns to the binding, and assigning to a const throws:
const items = ["a", "b"];
const fns = [];
for (const item of items) {
fns.push(() => item);
}
console.log(fns.map(f => f())); // ["a", "b"]
try {
for (const c = 0; c < 3; c++) {
console.log("body ran with", c); // runs once: body ran with 0
}
} catch (e) {
console.log(e.name); // "TypeError"
}The body runs once before the error. The failure happens at c++, not at the declaration.
for...in and for...of with var Share One Binding Too
The bug is not limited to counting loops. for (var key in obj) and for (var x of arr) hoist a single binding, and closures made in the body will all see the last key or element.
Performance Is Not a Reason to Avoid let
Engines skip the per-iteration copy when no closure captures the loop variable. In practice, a let loop with no closures performs about the same as a var loop.
Exercise
What does this print, and why? const out = []; for (var i = 0; i < 3; i++) { let j = i; out.push(() => i + j); } console.log(out.map(f => f()));
Show answer
It prints [3, 4, 5]. The variable i is a single function-scoped var binding that ends at 3, so every closure reads 3 for i. The variable j is a let declared inside the block, so each pass through the body creates a new j holding 0, 1, and 2. The sums are 3+0, 3+1, and 3+2.
Exercise
A teammate writes let idx = 0; for (; idx < buttons.length; idx++) { buttons[idx].onclick = () => console.log(idx); } and every button logs buttons.length. They used let, so why does the bug still happen, and what is the smallest fix?
Show answer
The let declaration is outside the loop header, so no per-iteration copy is made and all handlers share one binding that ends at buttons.length. Move the declaration into the header with for (let idx = 0; idx < buttons.length; idx++), or add const current = idx; inside the body and log current.
Exercise
Predict the output: const fs = []; for (let i = 0; i < 4; i++) { fs.push(() => i); i += 1; } console.log(fs.map(f => f()));
Show answer
It prints [1, 3]. Iteration 1 starts with i = 0, pushes a closure, then sets that binding to 1. The value 1 is copied to the next iteration and incremented to 2. The body pushes a closure and sets that binding to 3. The next copy becomes 4 and fails the test. Each closure reads the final value of its own iteration's binding.