JavaScript · Middle · Question 12 of 75

What does this code print?

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

Explanation

var creates one variable for the whole function, and by the time the timers fire, the loop has finished with i = 3. With let, each iteration gets a new binding and the output is 0 1 2.

Further reading

Problem with a question

JavaScript · Middle · question 12

Test yourself

Take the JavaScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz