I can't figure out the output of the following two loops. The only difference I notice is that the former use var and assigns a global scope and later create a local scope using const.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}
the output is 3 3 3 and 0 1 2.
According to my shallow knowledge, the first loop has to output 0 1 2.
If I print the value of i in the first loop.
for (var i = 0; i < 3; i++) {
  console.log(i);
  setTimeout(() => console.log(i), 1);
}
the output printed in the console by first console.log(i) is 0 1 2. While in the one wrapped within setTimeout vary.
Why?
 
    