Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does var in a loop with setTimeout print 3 3 3?

Do you know what will be the output of this code?

JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
Show answer and explanation

The answer is 3 3 3.

var creates a single i for the whole loop. The callbacks run after the loop has finished, when i is already 3, and all three closures read that same variable.

Changing var to let prints 0 1 2.

Take the full quiz Next question →

More Closures questions

  1. How does a closure counter work in JavaScript?
  2. Why does let in a for loop fix the setTimeout closure problem?
  3. Do two closures from the same function share state?
  4. Does a JavaScript closure capture the value or the variable?
  5. How do closures create private variables in JavaScript?

Related topics