I checked the questions and answers about the same problem but non of them answered my question, so please don't discard my question.
When "i" is declared as a let variable, for each iteration, JS creates a new binding of "i" , thus each function of the SetTimout has it's own "i" inside it's closure (in opposite to the situation where "i" is declared as a var variable where all the SetTimout functions share the same binding in their closure). The question is : If JS creates a new binding of "i" at each iteration of the for loop when using let, so how the incremented value is transmitted to the new binding of i ?
How the new binding of i is instantiated with the present value of i?
Do we really have two binding of i in different scopes with different values if yes what are those scopes?
Thanks in advance
function a() {
for (let i = 0; i < 3; i++) {
setTimeout(function () { console.log(i) }, i * 1000);
}
}
a();
If JS creates a new binding of "i" at each iteration of the for loop when using let, so how the incremented value is transmitted to the new binding of i ?
At the end of the iteration, the values get copied over from the previous environment record to the next one.
Do we really have two binding of i in different scopes with different values if yes what are those scopes?
I'd like to introduce the term environment record here, which is the term the specification uses to describe the "thing" which binds values. There are multiple environment records (one for each iteration), all of them have the same scope (the values can be accessed inside the loop's body), and possibly different lifetimes and values.
You'll find all this in ES262, 13.7.4.9 Runtime Semantics: CreatePerIterationEnvironment