CodePark/ questions / Closures
START PRACTICINGPRACTICE
Frontend question · JavaScript › Closures

What does this log?

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

var creates one function-scoped i that all three callbacks share. The callbacks run after the loop has finished, and by then i is already 3. So each one logs 3.

The tempting option "0 1 2" is wrong for
var. You would get 0 1 2 with let, because let creates a new i for each loop iteration.