Sub topic 6
Closures in Callbacks and the Loop Variable Trap
This chapter assumes you can write arrow functions, know how let, const, and var are scoped, and know from earlier chapters that a setTimeout callback runs only after the current synchronous code finishes. The examples run in Node.js or a browser console.
When you write a callback, you almost always use variables from the code around it. A callback that logs a user's name has to find name somewhere. Usually that just works. It breaks when the variable changes between the moment you create the callback and the moment it runs. This chapter explains how callbacks capture variables, why the classic for (var i ...) loop logs the wrong numbers, and how to fix that bug and the less obvious ones related to it.
What a Closure Is
A closure is a function together with the variable scope it was created in. When JavaScript creates a function, the function keeps a hidden reference to the environment where it was defined. When the function later reads a variable that isn't its own parameter or local, it looks the variable up through that reference.
This means a callback can still use variables after the function that declared them has returned:
function makeLogger(prefix) {
let calls = 0;
return function log(message) {
calls++;
console.log(`${prefix} #${calls}: ${message}`);
};
}
const info = makeLogger('INFO');
setTimeout(() => info('first'), 0);
setTimeout(() => info('second'), 0);
// INFO #1: first
// INFO #2: secondmakeLogger returned long before either timer fired, but prefix and calls stayed alive because log still refers to them. Both timer callbacks share the same calls variable, so the count keeps going up.
Closures Capture Variables, Not Values
This rule causes most closure bugs: a closure holds a reference to the variable itself, not a copy of its value at creation time. The callback reads whatever value the variable has when the callback runs.
With a synchronous callback the difference rarely shows, because the callback runs right away. With an asynchronous callback, other code can run in between:
let status = 'pending';
setTimeout(() => console.log('status is', status), 0);
status = 'done';
// status is doneThe arrow function was created while status was 'pending', but it runs after the assignment, so it logs 'done'. If you need a snapshot of the current value, copy it somewhere that won't change. One way is to pass it as an extra argument to setTimeout. JavaScript evaluates the extra arguments when setTimeout is called, not when the timer fires:
let status = 'pending';
setTimeout((s) => console.log('status was', s), 0, status);
status = 'done';
// status was pendingThe Loop Variable Trap
The best-known version of this bug comes from scheduling callbacks inside a loop:
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` logs 3 three times
var is function-scoped (or global-scoped at the top level). The whole loop has exactly one i. Each of the three arrow functions closes over that same variable. The loop runs to completion synchronously: it schedules three timers, increments i to 3, sees that 3 < 3 is false, and exits. Only then does the event loop run the timer callbacks. Each one looks up i, finds 3, and logs it.
The callbacks did nothing wrong. They read the variable they captured. The bug is that all three captured the same variable.
Why `let` fixes it
A let declared in the head of a for loop gets special treatment. The language creates a new binding for each iteration. At the start of every iteration, the engine makes a fresh environment, copies the current value of j into it, and the loop body and any closures created in it use that iteration's copy. The increment j++ then runs against the next iteration's fresh copy, so earlier copies keep their values.
When `let` does not save you
The per-iteration binding exists only when the let is declared in the loop head. If you declare it outside, you are back to one shared variable:
let k;
for (k = 0; k < 3; k++) {
setTimeout(() => console.log('outer let', k), 0);
}
// outer let 3
// outer let 3
// outer let 3const in a classic counting loop doesn't work either, because the update expression tries to reassign it:
try {
for (const n = 0; n < 3; n++) {
console.log('body', n);
}
} catch (err) {
console.log(err.name, err.message);
}
// body 0
// TypeError Assignment to constant variable.for...of and for...in with const work fine, because each iteration declares a new binding and nothing reassigns it:
for (const name of ['ana', 'ben', 'cy']) {
setTimeout(() => console.log('hello', name), 0);
}
// hello ana
// hello ben
// hello cywhile and do...while loops get no per-iteration binding at all. If you schedule callbacks inside one, declare a block-scoped copy inside the body: const current = i;.
Fixes That Predate `let`
You will still meet the var version in older code, transpiled output, and interview questions. Every fix below does the same thing: it gives each callback its own variable to capture.
function show(label, n) {
console.log(label, n);
}
// 1. IIFE: a new function scope per iteration
for (var a = 0; a < 3; a++) {
(function (captured) {
setTimeout(() => show('iife', captured), 0);
})(a);
}
// 2. Extra setTimeout argument: value evaluated at scheduling time
for (var b = 0; b < 3; b++) {
setTimeout(show, 0, 'arg', b);
}
// 3. bind: arguments are fixed when bind is called
for (var c = 0; c < 3; c++) {
setTimeout(show.bind(null, 'bind', c), 0);
}
// 4. forEach: each call of the callback has its own parameter
[0, 1, 2].forEach((d) => {
setTimeout(() => show('forEach', d), 0);
});Each version logs 0, 1, 2 for its label. Timers with equal delays run in the order they were scheduled, so the output appears grouped by label.
| Fix | How it isolates the value | When to use it |
|---|---|---|
| `let` in the loop head | New binding per iteration | Default choice in modern code |
| `const` in `for...of` | New binding per iteration | Iterating arrays, Maps, Sets |
| IIFE | New function scope per call | Legacy ES5 code without a build step |
| Extra `setTimeout` arguments | Values copied at call time | Timers only |
| `bind` with arguments | Arguments fixed at bind time | Passing a named function as the callback |
| `forEach` / `map` | Each callback call gets its own parameter | Array work that already uses array methods |
The Shared Object Trap
let gives each iteration its own binding, but if every binding points to the same object, the callbacks still share data. A closure captures the variable. It does not clone the object behind it.
const results = [];
const row = {};
for (let i = 0; i < 3; i++) {
row.id = i;
setTimeout(() => results.push(row.id), 0);
}
setTimeout(() => console.log(results), 0);
// [ 2, 2, 2 ]Every callback reads row.id from one object, and the last write was 2. Changing the loop to let would not help, because row was never the loop variable. The fix is to create the object inside the loop body so each iteration has its own object, or to read the value into a block-scoped constant:
const results = [];
for (let i = 0; i < 3; i++) {
const row = { id: i };
setTimeout(() => results.push(row.id), 0);
}
setTimeout(() => console.log(results), 0);
// [ 0, 1, 2 ]The same bug shows up with reused buffers, mutable configuration objects, and request objects that get changed while a callback is waiting. If a callback must see the data as it was when the callback was scheduled, copy the data ({ ...obj }, structuredClone(obj)) or pull out the primitive fields before scheduling.
Stale Closures
The opposite problem also happens. A callback captures a variable whose binding is replaced, while the callback keeps reading the old one. This is common with long-lived callbacks such as event listeners and intervals:
function startReporter(settings) {
const interval = settings.interval;
const id = setInterval(() => {
console.log('reporting every', interval, 'ms');
}, interval);
return id;
}
let settings = { interval: 100 };
const id = startReporter(settings);
settings = { interval: 5000 }; // the running interval never sees this
setTimeout(() => clearInterval(id), 350);
// reporting every 100 ms (logged three times)Reassigning settings creates a new object and a new value for the outer variable. The interval callback closed over interval inside startReporter, which never changes. When a callback needs to see updates, have it read through a reference that stays the same (for example, a property of an object it keeps), or tear down the old callback and register a new one.
Closures and Memory
A closure keeps the variables it uses alive for as long as the closure itself is reachable. A timer callback is released once it has run. An event listener or setInterval callback stays reachable until you remove it, so everything it captures stays in memory too.
const { EventEmitter } = require('node:events');
const bus = new EventEmitter();
function attach() {
const bigBuffer = Buffer.alloc(50 * 1024 * 1024);
const size = bigBuffer.length; // keep only what the listener needs
bus.on('report', () => console.log('buffer size was', size));
}
attach();
bus.emit('report');
// buffer size was 52428800Here the listener references only size, so engines such as V8 can free the 50 MB buffer after attach returns. If the listener used bigBuffer.length directly, the buffer would live as long as the listener.
A Checklist for Callbacks That Capture Variables
- Ask whether the callback runs now (synchronous) or later (asynchronous). Only the second kind can see changed values.
- Check every outer variable the callback reads. Can anything reassign it before the callback runs?
- In loops, declare the loop variable with
letin the head, orconstinfor...of. - For objects, check whether the callback needs the live object or a snapshot.
- For long-lived callbacks, check what they keep in memory and how they are removed.
Exercise
Predict the output, then explain it. var tasks = []; for (var i = 0; i < 3; i++) { tasks.push(() => i * 10); } console.log(tasks.map((t) => t())); Now change only one keyword so that it prints [ 0, 10, 20 ].
Show answer
It prints [ 30, 30, 30 ]. All three arrow functions close over the single function-scoped i, and the loop has finished, leaving i at 3, before tasks.map calls any of them. This shows the trap needs no timers: the callbacks only have to run after the loop. Changing var i to let i in the loop head gives each iteration its own binding, so the output becomes [ 0, 10, 20 ].
Exercise
This code uses let, yet logs "user carol" three times. Why, and how do you fix it? const current = { name: '' }; for (const name of ['ana', 'ben', 'carol']) { current.name = name; setTimeout(() => console.log('user', current.name), 0); }
Show answer
Each iteration has its own name binding, but the callbacks don't read name. They read current.name, and current is a single object that the loop overwrites, finishing with 'carol' before any timer fires. To fix it, make the callback capture the per-iteration binding (console.log('user', name)) or create a new object in each iteration (const current = { name }; inside the loop).
Exercise
Rewrite this ES5 loop so it logs 0, 1, 2 without using let, const, or arrow functions. Name the technique you used. for (var i = 0; i < 3; i++) { setTimeout(function () { console.log(i); }, 0); }
Show answer
One fix is an IIFE that creates a new function scope per iteration:
for (var i = 0; i < 3; i++) {
(function (n) {
setTimeout(function () { console.log(n); }, 0);
})(i);
}
Other valid ES5 answers: pass i as the third argument to setTimeout (setTimeout(function (n) { console.log(n); }, 0, i);), or bind it (setTimeout(console.log.bind(console, i), 0);). Each one copies the current value into a new variable or argument before the loop changes i.