What does the following code output? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }

JavaScript Developer Medium

JavaScript Developer — Medium

What does the following code output? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }

Key points

  • The setTimeout function is asynchronous and runs after the loop completes.
  • The value of i is 3 when the setTimeout function executes.
  • This behavior is due to JavaScript's event loop mechanism.

Ready to go further?

Related questions