How is a new scope created for Let in a for loop

时间:2018-06-04 16:53:20

标签: javascript variables for-loop closures let

    for (let i = 0; i 10; ++i) {
    setTimeout(_ => {
        console.log(i);
    }, 100*i);
}

I have been reading about hoisting and variable scoping but do not quite understand the above solution, I've looked into many websites including the answers given as duplicate but not found an explanation that quite helps me easily understand.

1 - I understand that let is block scoped, however the scope here is between the opening and closing curly braces of the for loop right?

2 - Since the let is declared outside of these curly braces, on each iteration shouldn't it be the same let variable which is being incremented? just as if it was a var?

3 - On one of the answers, it's mentioned

i gets a new binding for every iteration of the loop.

What exactly does this mean? the answer doesn't go into detail to explain this.

4 - Are 10 different for loop iteration environments being created here, each with a different variable i?

5 - This was another comment on one of the top answers which shows how confusing this is and I didn't understand, can anyone explain please?

Oddly though, while it is a separate instance if i in each iteration of the loop, any modification of i within the loop still affects the loop's iteration count. It's an odd beast, half separate variable, half reference to the original

It's easy to point to duplicate answers but if they don't explain it in a way someone understands, those answers don't help.

0 个答案:

没有答案