Sub topic 9
Loops, Closures, and the Classic var Bug
This chapter assumes you know what closures are at a basic level: a function that keeps access to variables from the scope where it was created. It also assumes you are comfortable with for loops, arrow functions, and setTimeout, and that you have read the earlier chapters on function scope (var) and block scope (let and const).
This chapter covers the most famous bug caused by var and explains exactly why let fixes it. The rule behind the fix also explains several less obvious cases, such as while loops, const in loop headers, and code that changes the loop variable inside the body.
What a Closure Actually Captures
A closure does not take a snapshot of a variable's value. It keeps a reference to the binding, which is the named slot that holds the value. When the closure runs later, it reads whatever value is in that slot at that moment.
let message = 'hello';
const read = () => message;
message = 'goodbye';
console.log(read()); // 'goodbye': the closure reads the binding when it runsKeep this in mind for the rest of the chapter. Every loop question here comes down to one thing: how many bindings exist, and which one did each closure capture?
The Classic Bug
Here is the bug in its best-known form. You schedule some work inside a loop, and every callback reports the same number.
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log('var:', i);
}, 0);
}
// var: 3
// var: 3
// var: 3You get the same result without timers when you store functions in an array and call them later:
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(f => f())); // [3, 3, 3]Why it prints 3 three times
Two facts combine to cause this:
- There is only one
i.varis function-scoped (or global at the top level). The loop does not create a newion each pass. All three arrow functions close over the same binding. - The callbacks run after the loop finishes. By the time any callback runs, the loop has already incremented
ito3, failed the test3 < 3, and exited.
So three closures read one slot, and that slot holds 3. The value 3 can look odd because the loop body never ran with i === 3. It is simply the value that made the loop condition false.
The let Fix
Change one keyword and the behavior changes:
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(f => f())); // [0, 1, 2]
for (let k = 0; k < 3; k++) {
setTimeout(() => console.log('let:', k), 0);
}
// let: 0
// let: 1
// let: 2This is not just a side effect of block scoping. A plain block scope around the loop body would not be enough by itself, because j is declared in the loop header and not in the body. The language specification gives for loops with let declarations a special rule: each iteration gets its own fresh copy of the loop variable.
How the per-iteration copy works
For for (let j = 0; j < 3; j++), the engine works roughly like this:
- It runs the initializer
let j = 0in a new environment. - It creates a fresh environment for the first iteration and copies the current value of
jinto it. - It runs the test
j < 3, then the body. Closures created in the body capture this iteration'sj. - It creates a new environment for the next iteration and copies the current value of
jinto it. - It runs the increment
j++on the new copy, then goes back to the test.
Step 5 is the important part. The increment changes the next iteration's binding, so the previous iteration's binding keeps the value it had when its body ended.
Edge case: changing the variable inside the body
Because the copy happens after the body and before the increment, a closure sees the value its binding had at the end of its own iteration. Changes made inside the body count. Changes made by the increment do not.
const fns = [];
for (let i = 0; i < 5; i++) {
fns.push(() => i);
i++; // modifies this iteration's binding after the closure was created
}
console.log(fns.map(f => f())); // [1, 3, 5]Trace it:
| Iteration | `i` at start of body | `i` after `i++` in body | Closure sees | Next copy after increment |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 2 |
| 1 | 2 | 3 | 3 | 4 |
| 2 | 4 | 5 | 5 | 6 (test fails) |
Each closure still reads its binding live. The binding just stops changing once its iteration ends.
Other Loop Forms
The per-iteration rule applies to more than the classic three-part for loop.
for...of and for...in
With let or const, for...of and for...in also create a new binding for each iteration. With var, they share one binding, just like the classic loop.
const items = ['a', 'b', 'c'];
const ofVar = [];
for (var item of items) {
ofVar.push(() => item);
}
console.log(ofVar.map(f => f())); // ['c', 'c', 'c']
const ofConst = [];
for (const entry of items) {
ofConst.push(() => entry);
}
console.log(ofConst.map(f => f())); // ['a', 'b', 'c']const works in for...of and for...in because the loop never reassigns a binding. It creates a new one each time and initializes it with the next value.
const in a classic for loop
const in a three-part for loop is a different matter. The increment expression tries to reassign the binding:
try {
for (const n = 0; n < 3; n++) {
console.log('body ran with', n); // runs once
}
} catch (e) {
console.log(e.name); // 'TypeError'
}The body runs once with n === 0. The error appears when n++ runs. This catches people out because the failure happens after the first iteration and not when the loop starts.
while and do...while loops
while loops have no header declaration, so there is no per-iteration copy. A let declared outside the loop is one binding, and it causes the same bug as var:
let k = 0;
const shared = [];
while (k < 3) {
shared.push(() => k);
k++;
}
console.log(shared.map(f => f())); // [3, 3, 3]Writing let is not enough by itself. What matters is where the binding lives. To fix a while loop, declare a block-scoped variable inside the body. The body is a block, so each pass creates a new binding:
let m = 0;
const separate = [];
while (m < 3) {
const current = m; // a new binding on every pass through the block
separate.push(() => current);
m++;
}
console.log(separate.map(f => f())); // [0, 1, 2]| Loop form | Declaration | Bindings created | Closures see |
|---|---|---|---|
| `for (var i ...)` | `var` in header | One, function-scoped | Final value |
| `for (let i ...)` | `let` in header | One per iteration | Each iteration's value |
| `for (const i ...; i++)` | `const` in header | n/a | `TypeError` on increment |
| `for (const x of ...)` | `const` in header | One per iteration | Each element |
| `for (var x of ...)` | `var` in header | One, function-scoped | Last element |
| `while` with outer `let` | `let` outside loop | One | Final value |
| `while` with inner `const` | `const` in body | One per iteration | Each iteration's value |
Fixes Before let Existed
You will still see these patterns in older code and in code compiled for old environments. Knowing them helps you read that code, and they show the same principle: make a new binding for each iteration.
Immediately invoked function expression (IIFE)
A function call creates a new scope, and its parameter is a new binding each time:
var legacyFns = [];
for (var i = 0; i < 3; i++) {
(function (captured) {
legacyFns.push(function () {
return captured;
});
})(i);
}
console.log(legacyFns.map(function (f) { return f(); })); // [0, 1, 2]Callback-based iteration
Array.prototype.forEach calls your callback once per element. Each call has its own parameter bindings:
var viaForEach = [];
[0, 1, 2].forEach(function (value) {
viaForEach.push(function () { return value; });
});
console.log(viaForEach.map(function (f) { return f(); })); // [0, 1, 2]Passing the value as an argument
setTimeout passes any extra arguments to the callback. The value is copied into the callback's parameter when the timer is scheduled:
for (var t = 0; t < 3; t++) {
setTimeout(function (value) {
console.log('arg:', value);
}, 0, t);
}
// arg: 0
// arg: 1
// arg: 2Where This Bug Shows Up in Practice
The array-of-functions example is a teaching device. Real bugs usually involve callbacks that run later:
- Event handlers attached in a loop, for example one click handler per button, where every handler reports the last index.
- Timers and retries, where each scheduled attempt should know its own attempt number.
- Promise callbacks created in a loop, such as
.then()handlers that log which request finished.
The async/await version behaves the same way. A let loop variable gives each awaited step the correct value. A var variable used in a callback after an await can show a later value if the loop has moved on in the meantime.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run() {
const pending = [];
for (let attempt = 1; attempt <= 3; attempt++) {
pending.push(wait(10).then(() => `attempt ${attempt} done`));
}
console.log(await Promise.all(pending));
// ['attempt 1 done', 'attempt 2 done', 'attempt 3 done']
}
run();Debugging Checklist
When closures created in a loop all report the same value:
- Find the variable the closure reads.
- Ask where that binding is declared. Is it
var, or aletoutside the loop? - If it is in a
forheader, changevartolet(or toconstforfor...ofandfor...in). - If it is a
whileloop, copy the value into aconstdeclared inside the body. - If you cannot change the declaration, pass the value into a function parameter (IIFE,
forEach, or a callback argument).
Exercise
Predict the output of this code, and explain it in terms of bindings: const out = []; for (var i = 0; i < 2; i++) { let snapshot = i; out.push(() => [i, snapshot]); } console.log(out.map(f => f()));
Show answer
It prints [[2, 0], [2, 1]]. The variable i is declared with var, so there is one shared binding, and it holds 2 after the loop ends. The variable snapshot is declared with let inside the body block, so each iteration creates a new binding that holds that iteration's value of i (0, then 1). Each closure reads the shared i and its own snapshot.
Exercise
This code logs "item 3" three times. Fix it two ways: once by changing only a declaration keyword, and once without using let or const for the index. Code: var labels = ['x', 'y', 'z']; for (var idx = 0; idx < labels.length; idx++) { setTimeout(function () { console.log('item ' + idx); }, 0); }
Show answer
Fix 1: change for (var idx = 0; ...) to for (let idx = 0; ...), which gives each iteration its own idx binding, so it logs item 0, item 1, item 2. Fix 2: pass the value as a timer argument, as in setTimeout(function (n) { console.log('item ' + n); }, 0, idx);. You could also wrap the setTimeout call in an IIFE such as (function (n) { setTimeout(function () { console.log('item ' + n); }, 0); })(idx);. Either way, each callback gets its own parameter binding.
Exercise
What does this print, and why? const fns = []; for (let i = 0; i < 4; i += 2) { fns.push(() => i); i += 1; } console.log(fns.map(f => f()));
Show answer
It prints [1, 4]. In iteration one, i starts at 0, the closure is created, and the body sets i to 1. That binding is then left alone, so the closure sees 1. The value 1 is copied into a new binding, and the increment makes it 3. In iteration two, i is 3 (3 < 4), the closure is created, and the body sets i to 4. Then the copy plus increment gives 6, the test fails, and the loop stops. Each closure sees its binding's value at the end of its own iteration body.