What is the output of following?
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); }
for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); }
Explanation
In the first loop we defined i
using var, its value is scoped to its function(or global scope if its not declared inside a function) , when setTimeout
gets called after loop finishes, the value of i
has already reached to 3
, so loop prints 3 3 3
. In second loop, we defined i
using let, so it’s value is block scoped, during each iteration i
will have a new value scoped inside loop, so it prints 0 1 2