Pointer Walk

JavaScript Closures in Loops

Three timers in a loop all print 3. Every callback shares one variable, and the loop has finished before any of them runs.

Languages and RuntimesBeginner7 min read

Three timers in a loop

What does this print?

js
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

It looks as if it should print 0, 1, 2. It prints 3, 3, 3.

Two separate facts combine to cause this. Either one alone would be harmless.

Fact 1: a function remembers variables, not values

When a function uses a variable from outside itself, it does not take a copy of the value at that moment. It keeps a link to the variable itself, and reads whatever is in it when the function finally runs.

A function together with the outside variables it holds on to is called a closure.

js
let count = 0;
const show = () => console.log(count);

count = 5;
show();        // 5, not 0

show was created when count was 0. It prints 5, because it looks the variable up when it is called.

Fact 2: the timers run later

setTimeout(fn, 0) does not run fn immediately, even with a delay of zero. It puts fn in a queue to be run after the current code has finished. The whole loop completes first.

Put them together

Three timers with varInteractive
1for (var i = 0; i < 3; i++) {
2 setTimeout(() => console.log(i), 0);
3}
4// the loop has finished
5// now the timers run

Variables that exist

nothing yet

Start. Press play, or step through one line at a time.

  1. var creates a single i for the entire loop

    There is one variable, and each pass changes it.

  2. Each pass creates a function linked to that one i

    Three functions, all pointing at the same variable.

  3. The loop finishes

    The last i++ makes i equal to 3, the test i < 3 fails, and the loop stops.

  4. Only now do the timers run

    Each one reads i. It is 3.

The functions were made at different moments, but they are all asked the same question at the same later time, about the same variable.

The fix: let

Change one word.

js
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
Three timers with letInteractive
1for (let i = 0; i < 3; i++) {
2 setTimeout(() => console.log(i), 0);
3}
4// the loop has finished
5// now the timers run

Variables that exist

nothing yet

Start. Press play, or step through one line at a time.

let is scoped to the block. In a for loop, JavaScript goes one step further and creates a fresh i for every pass, copying the value across. Each function is linked to its own variable, which nothing changes afterwards. The output is 0, 1, 2.

varlet
Lives inThe whole functionThe nearest block { }
In a for loopOne variable shared by all passesA new variable for each pass
The three timers print3 3 30 1 2

The same trap elsewhere

Any time a function is created in a loop and run later, the same thing can happen: click handlers added in a loop, callbacks for network requests, promises. Other languages have it too. Python closures in a loop behave like var:

python
actions = [lambda: print(i) for i in range(3)]
for action in actions:
    action()        # 2 2 2

The cure is always the same: give each function its own variable.

Closures are useful, not just a trap

The behaviour that caused this bug is also one of the most useful things in the language. A function that remembers its surroundings can keep private state:

js
function makeCounter() {
  let count = 0;
  return () => ++count;
}

const next = makeCounter();
next();   // 1
next();   // 2

Nothing outside can touch count. Only the returned function can.

Key takeaways

  • A closure is a function plus the outside variables it holds on to.
  • It holds the variable itself, not a copy of its value at the time.
  • With var, a loop has one variable, so every function created in it sees the final value.
  • With let, each pass gets its own variable, so each function sees its own value.
  • Watch for it whenever functions are created in a loop and run later.

Your progress

Check your progress

0%

  1. Read the page50% of this page

    When you have gone through the page and its animations, tick it off.

  2. Take the quiz50% of this page

    6 questions, from easy to hard. Take it as often as you like: the questions change, and only your best score counts.

Saved on this device only. See all your progress