Sub topic 6
Closures in Callbacks and the Loop Variable Trap
This chapter assumes you know how let, const, and var are scoped, and that you have seen how setTimeout defers a callback until the current synchronous code finishes. Earlier chapters covered both.
What a Closure Captures
A closure is a function together with the variables from the scope where it was created. When you write a callback inside another function, the callback can read and change the variables of that outer function, even after the outer function has returned.
The callback holds a reference to the variable itself. It does not copy the variable's value. When the callback finally runs, it reads whatever value the variable holds at that moment.
function makeGreeter() {
let name = 'Ada';
setTimeout(() => console.log('Hello,', name), 0);
name = 'Grace';
}
makeGreeter();
// Hello, GraceThe arrow function was created while name was 'Ada'. It ran later, after name changed to 'Grace', so it logged the current value. With synchronous callbacks this rarely matters, because they run right away. With asynchronous callbacks there is a gap between creating the callback and running it, and the variable can change during that gap.
The Loop Variable Trap
This gap causes the best-known closure bug in JavaScript:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var', i), 0);
}
// var 3, var 3, var 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let', j), 0);
}
// let 0, let 1, let 2Why `var` gives 3, 3, 3
A var declaration is scoped to the enclosing function, or to the global scope, and never to the loop body. The whole loop has a single i. All three callbacks close over that one variable. The loop runs to completion before any timer callback gets a turn. By the time they run, i has been incremented to 3, the value that ended the loop.
Why `let` gives 0, 1, 2
A let declaration in a for loop header gets special treatment. The engine creates a fresh binding of j for each iteration and copies the current value into it. Each callback closes over its own iteration's j, and that j never changes afterward.
Fixes
Using let is the simplest fix. Older code, and code that can't change how a variable is declared, uses one of the other options in this table.
| Fix | How it works | When to use |
|---|---|---|
| `let` in the loop header | New binding per iteration | Default choice in modern code |
| `forEach` or `map` | Each call to the callback gets its own parameter | Iterating over an array |
| Function wrapper (IIFE) | A new function scope per iteration captures the value | Legacy ES5 code |
| Pass the value as an argument | `setTimeout(fn, 0, i)` passes the current value to `fn` | Timer APIs that accept extra arguments |
// IIFE: each call creates a new scope holding its own copy
for (var i = 0; i < 3; i++) {
(function (captured) {
setTimeout(() => console.log('iife', captured), 0);
})(i);
}
// iife 0, iife 1, iife 2
// forEach: index is a fresh parameter on each call
['a', 'b', 'c'].forEach((item, index) => {
setTimeout(() => console.log(index, item), 0);
});
// 0 a, 1 b, 2 c
// Extra setTimeout arguments are passed to the callback
for (var k = 0; k < 3; k++) {
setTimeout((n) => console.log('arg', n), 0, k);
}
// arg 0, arg 1, arg 2Closures Over Mutable Objects
let gives each iteration a new binding, but it does not copy objects. If every iteration closes over a different binding that refers to the same object, and that object is mutated, all callbacks see the mutation:
const state = { step: 0 };
for (let n = 0; n < 3; n++) {
const snapshot = state;
state.step = n;
setTimeout(() => console.log('step', snapshot.step), 0);
}
// step 2, step 2, step 2To keep per-callback values, capture a primitive (const step = state.step) or make a copy ({ ...state }).
Exercise
What does this code log, and what is the smallest change that makes it log 0, 1, 2? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }
Show answer
It logs 3 three times. All callbacks share one function-scoped i, and the loop has already set it to 3 when the timers fire. Changing var to let gives each iteration its own binding, so the callbacks log 0, 1, 2.
Exercise
A function sets let status = 'pending', schedules setTimeout(() => console.log(status), 0), and then sets status = 'done'. What is logged, and why doesn't let prevent it?
Show answer
It logs 'done'. The callback closes over the status variable itself, not a copy of its value. let only creates a new binding per iteration in loop headers. Here a single binding exists and is reassigned before the callback runs.