I understand that let
prevents duplicate declarations which is nice.
let x;
let x; // error!
Variables declared with let
can also be used in closures which can be expected
let i = 100;
setTimeout(function () { console.log(i) }, i); // '100' after 100 ms
What I have a bit of difficulty grasping is how let
applies to loops. This seems to be specific to for
loops. Consider the classic problem:
// prints '10' 10 times
for (var i = 0; i < 10; i++) { process.nextTick(_ => console.log(i)) }
// prints '0' through '9'
for (let i = 0; i < 10; i++) { process.nextTick(_ => console.log(i)) }
Why does using let
in this context work? In my imagination even though only one block is visible, for
actually creates a separate block for each iteration and the let
declaration is done inside of that block ... but there is only one let
declaration to initialize the value. Is this just syntactic sugar for ES6? How is this working?
I understand the differences between var
and let
and have illustrated them above. I'm particularly interested in understanding why the different declarations result in different output using a for
loop.