What does this JavaScript closure log?

Consider this snippet.

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

What gets logged, and what tiny change would make it log 0, 1, 2.

MechaPrime

It logs 3 three times because var shares one loop variable, and changing var i to let i gives each iteration its own binding so you get 0, 1, 2.

Arthur

One caveat is that setTimeout(..., 0) still runs after the loop finishes, so with var every callback reads the final i, while an IIFE also fixes it if you need to support older code.

Sora