Sub topic 8
The Classic Loop Bug and How to Fix It
This chapter assumes you know the difference between var and let scoping. It also assumes you have seen that closures capture variables rather than copies of their values. Here those two ideas combine into one of the most common JavaScript bugs.
The Bug
You want three timers that log 0, 1, and 2. This code looks like it should do that:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 0);
}
// var: 3, var: 3, var: 3Every callback prints 3. Two facts explain why:
varis function-scoped, so the loop creates only onei. All three arrow functions close over that same variable.setTimeoutcallbacks run after the loop finishes. By thenihas been incremented to 3, the value that ended the loop.
The callbacks do not store the value i had when they were created. They read the shared variable when they run, and at that point it holds 3.
Fix 1: Use let
let is block-scoped, and a for loop with a let header creates a fresh binding for each iteration. Each callback closes over its own copy.
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 0);
}
// let: 0, let: 1, let: 2Use this fix in modern code. It needs no extra functions and states what you mean.
Fix 2: Create a Function Scope
Before ES2015, the only way to get a new scope was to call a function. An immediately invoked function expression (IIFE) passes the current value in as a parameter. The parameter is a new variable on every call.
for (var i = 0; i < 3; i++) {
(function (n) {
setTimeout(() => console.log('iife:', n), 0);
})(i);
}
// iife: 0, iife: 1, iife: 2You will see this pattern in older codebases. It works for the same reason the let fix works: each callback closes over a different variable.
Fix 3: Let an Array Method Do It
Array methods such as forEach call your callback once per element. Each call gets its own parameters, so there is nothing shared to go wrong.
[0, 1, 2].forEach((n) => {
setTimeout(() => console.log('forEach:', n), 0);
});
// forEach: 0, forEach: 1, forEach: 2Choosing a Fix
| Fix | How it creates a new binding | When to use |
|---|---|---|
| `let` in loop header | Per-iteration block scope | Default choice in modern code |
| IIFE with parameter | New function call per iteration | Legacy code limited to `var` |
| `forEach` or `map` | New callback call per element | When you are already iterating an array |
Exercise
What does this code log, and why? let i; for (i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }
Show answer
It logs 3 three times. The variable is declared once outside the loop, so the header does not create a per-iteration binding. All three callbacks share the same i, which is 3 by the time they run.
Exercise
Rewrite for (var k = 0; k < 3; k++) { setTimeout(() => console.log(k), 0); } so it logs 0, 1, 2 while still declaring k with var.
Show answer
Wrap the body in an IIFE that takes the value as a parameter: for (var k = 0; k < 3; k++) { (function (n) { setTimeout(() => console.log(n), 0); })(k); }. Each call creates a new n, so each callback captures a different variable.