Predict the output · Node.js

var in a Loop with setTimeout

Easy Predict the output Most askedSeen at Meta, Amazon, Uber

What does this print? Then explain how to make it print 0 1 2.

What does this print?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
  1. 0
    1
    2
  2. 3
    3
    3
  3. 2
    2
    2
  4. undefined
    undefined
    undefined

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

3
3
3

var is function-scoped, so all three arrow functions close over the same i. The callbacks run after the loop has finished, when i is 3.

Fixes: use let (a new binding per iteration), or capture the value explicitly (setTimeout(console.log, 0, i) or an IIFE).