puzzle 03 · javascript

What does this log?

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

why

var is function-scoped, so all three callbacks close over the same binding. By the time the timers fire, the loop has finished and i is 3. Swap var for let and each iteration gets its own binding, logging 0 1 2.

Today's puzzlea new one every day, and a streak to keep