🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript The var-in-a-Loop Trap

A var in a loop is one shared variable for every round. Every function made in the loop closes over that same variable, so each one sees its last value.

The trap

The loop pushes three functions. Each one reads the same shared variable, so each one logs 3.

const loggers = [];
for (var i = 0; i < 3; i++) {
  loggers.push(function () { console.log(i); });
}
loggers[0]();
loggers[1]();
loggers[2]();

let fixes it

A let loop gives each round its own variable. Each function logs the value from its own round.

const loggers = [];
for (let i = 0; i < 3; i++) {
  loggers.push(function () { console.log(i); });
}
loggers[0]();
loggers[1]();
loggers[2]();

The classic timer shape

Timers make the trap easy to hit. All three callbacks run after the loop, when the shared variable is already 3.

for (var k = 0; k < 3; k++) {
  setTimeout(function () { console.log(k); }, 50);
}

Example

const bad = [];
const good = [];
for (var a = 0; a < 3; a++) { bad.push(function () { return a; }); }
for (let b = 0; b < 3; b++) { good.push(function () { return b; }); }
console.log(bad[0](), bad[1](), bad[2]());
console.log(good[0](), good[1](), good[2]());

Key points

  • var: a declaration that belongs to the whole function, not to one block
  • A loop with var reuses one variable for every round.
  • Functions made inside the loop all capture that one variable.
  • After the loop, the variable holds its last value.
  • let: a declaration that belongs to one block, so each round gets a fresh variable
  • A loop with let gives each function its own captured variable.

In this example, the var loop pushes three functions that all read the same variable. That variable ends at 3, so the first line prints 3 three times. The let loop gives each function its own variable, so the second line prints 0, 1, and 2.

Note

The trap shows up with timers and handlers, but the cause is the shared variable, not the timer.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Why do all three functions print 3 in the var loop?