Sub topic 8
The Classic Loop Bug and How to Fix It
This chapter assumes you can read setTimeout calls, know the difference between var and let from the earlier chapter on block and function scope, and accept the previous chapter's main point: a closure captures a variable, not a copy of its value. Together, those two ideas explain a bug almost every JavaScript developer hits at least once.
The Bug
You want three callbacks that each log their loop index. You write the obvious loop:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 0);
}
// var: 3
// var: 3
// var: 3You expected 0, 1, 2 and got 3, 3, 3. The same thing happens when the callbacks are click handlers, promise callbacks, or functions stored in an array to call later. Timers are not the cause. The cause is how many variables the loop creates.
Here is the same bug with no timers at all, which makes it easier to reason about:
var fns = [];
for (var i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map((f) => f())); // [ 3, 3, 3 ]Why It Happens
Two facts from earlier chapters combine here.
varis function-scoped. Avarin a loop header is declared once, in the scope of the enclosing function (or the global scope). The loop has no separate copy of it.- A closure keeps a reference to the variable itself. When the closure runs, it reads whatever value the variable holds at that moment.
So the loop creates three arrow functions, and all three close over the same single i. The loop keeps incrementing that i until the test i < 3 fails, which happens when i is 3. Only after the loop has finished do the callbacks run, and each one reads the shared i and finds 3.
The callbacks are not "late" in any mysterious way. They are working correctly. They read the current value of the only i that exists.
The Modern Fix: `let`
Change var to let and the output becomes what you expected:
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 0);
}
// let: 0
// let: 1
// let: 2This is more than let being block-scoped. The language specification gives for loops that use let in the header special treatment: each iteration gets a fresh binding of j. At the end of each iteration, before the increment expression runs, the engine creates a new environment for the next iteration and copies the current value of j into it. Then j++ runs on the new binding.
Each closure therefore captures a different variable, and nothing changes that variable after its iteration ends.
The Pre-ES2015 Fix: Create a Scope per Iteration
Before let, the only construct that created a new scope was a function. The standard fix was to call a function on each iteration and pass the current value in as a parameter. Parameters are new variables on every call, so each closure captures its own copy.
Using an IIFE
An immediately invoked function expression (IIFE) is a function that is defined and called in one step:
var fns = [];
for (var i = 0; i < 3; i++) {
(function (index) {
fns.push(() => index);
})(i);
}
console.log(fns.map((f) => f())); // [ 0, 1, 2 ]The closure captures index, not i. Each call to the IIFE creates a new index holding the value i had at that moment.
Using a Named Helper
An IIFE inside a loop is hard to read. A named factory function does the same job more clearly:
function makeLogger(index) {
return () => console.log('helper:', index);
}
for (var i = 0; i < 3; i++) {
setTimeout(makeLogger(i), 0);
}
// helper: 0
// helper: 1
// helper: 2Avoiding the Shared Variable Entirely
Some APIs pass the value in for you, so there is no shared loop variable to capture:
[0, 1, 2].forEach((n) => {
setTimeout(() => console.log('forEach:', n), 0);
});
for (var i = 0; i < 3; i++) {
// setTimeout passes extra arguments to the callback
setTimeout((n) => console.log('arg:', n), 0, i);
}forEach calls your callback once per element, and each call has its own parameter n. The second form gives the value to setTimeout right away, so the callback receives a parameter and never reads i.
Comparing the Fixes
| Fix | How it isolates the value | When to use it |
|---|---|---|
| `let` in the `for` header | New binding per iteration, defined by the spec | Default choice in modern code |
| `const` in `for...of` | New binding per iteration, cannot be reassigned | Iterating arrays, maps, sets |
| IIFE with a parameter | New function scope per call | Legacy ES5 code without a transpiler |
| Named factory function | New function scope per call | When the callback logic deserves a name |
| `forEach` or `map` | Callback parameter per element | Data already in an array |
| Extra `setTimeout` argument | Value passed in, no capture | Timers only |
Edge Cases That Still Bite
`let` Declared Outside the Loop
The per-iteration behavior applies only to bindings declared in the for header. If you move the declaration out, you get one binding again:
let k;
const fns = [];
for (k = 0; k < 3; k++) {
fns.push(() => k);
}
console.log(fns.map((f) => f())); // [ 3, 3, 3 ]let did not change anything here, because k lives in the outer block and the loop only assigns to it.
`while` Loops
A while loop has no header declaration, so it has no per-iteration copy. A counter declared outside is shared. The fix is to declare a fresh let or const inside the body. The body block is entered again on each iteration, so each pass creates a new binding:
const fns = [];
let n = 0;
while (n < 3) {
const current = n;
fns.push(() => current);
n++;
}
console.log(fns.map((f) => f())); // [ 0, 1, 2 ]If the closures captured n instead of current, every one would return 3.
Changing the Loop Variable Inside the Body
The per-iteration copy happens after the body runs. If the body modifies the loop variable, the closure for that iteration sees the modified value, and the next iteration starts from it:
const fns = [];
for (let i = 0; i < 5; i++) {
fns.push(() => i);
i++;
}
console.log(fns.map((f) => f())); // [ 1, 3, 5 ]Trace the first iteration. The binding starts at 0, the closure is pushed, and the body's i++ makes that binding 1. The engine then copies 1 into a new binding and runs the header's i++, which gives 2. The first closure still points to the old binding, so it returns 1. The same steps produce 3 and 5.
Capturing an Object Instead of a Primitive
Fresh bindings protect the variable, not the object it points to. If each iteration captures the same object and mutates it, every closure sees the final state:
const state = { step: 0 };
const fns = [];
for (let i = 0; i < 3; i++) {
state.step = i;
fns.push(() => state.step);
}
console.log(fns.map((f) => f())); // [ 2, 2, 2 ]There is only one state object. To fix this, copy the value you need into a per-iteration variable (const step = state.step;) or create a new object on each iteration.
Spotting the Bug in Real Code
The pattern always has the same shape. A function is created inside a loop, it runs after the loop moves on, and it refers to a variable that the loop keeps changing. When you review code, check every function created inside a loop and ask two questions:
- Does it run later, for example as a callback, handler, promise continuation, or stored function?
- Is each variable it reads a fresh binding for this iteration, or one that is shared across iterations?
If the answers are "later" and "shared", you have found the bug.
Exercise
What does this code log, and why? var out = []; for (var i = 0; i < 3; i++) { out.push(function () { return i * 10; }); } console.log(out[0](), out[2]());
Show answer
It logs 30 30. var creates one function-scoped i shared by all three functions. When they are called after the loop, i is 3, so each returns 3 * 10.
Exercise
Rewrite the loop from the previous question so it logs 0 20 without using let or const anywhere.
Show answer
Wrap the push in an IIFE that takes the index as a parameter: var out = []; for (var i = 0; i < 3; i++) { (function (n) { out.push(function () { return n * 10; }); })(i); } console.log(out[0](), out[2]());. Each IIFE call creates its own n, so the closures capture 0, 1, and 2.
Exercise
A teammate writes let count = 0; while (count < 3) { setTimeout(() => console.log(count), 0); count++; } and expects 0, 1, 2. What prints, and what is the smallest fix?
Show answer
It prints 3 three times, because count is declared outside the loop and all callbacks share it. The smallest fix is to add const current = count; inside the body and log current, which creates a new binding on each pass.
Exercise
Predict the output of const fns = []; for (let i = 0; i < 6; i++) { fns.push(() => i); i += 2; } console.log(fns.map(f => f()));
Show answer
[2, 5]. In the first iteration the binding starts at 0, the closure is pushed, and the body sets it to 2, which the first closure sees. The value 2 is copied into a new binding and incremented to 3. The second closure is pushed and the body sets that binding to 5. The value 5 is copied and incremented to 6, the test 6 < 6 fails, and the loop ends.