I am interested how for loop operate behind the scenes in ES6.
This is the basic example
var funcs = [];
for (let i = 0; i < 5; i++) {
funcs.push(function () {
console.log(i);
});
};
The reason each function will get proper i value (from 0 to 4) is because let is creating 5 new scopes and functions are bound to their corresponding scope. Thats what I think and that makes most sense to me. If that is the case then it doesnt make sense why const declaration (i) is failing since it should be creating 5 new scopes and const variables can live happily in different scopes. Before let we have do use IIFE in order to achieve the same effect, but what that code did is that it basically created new scopes for the functions and I thought let is doing the same behind the scenes.
If the above statement is not correct, then it must be that let inside for loop is only creating one scope but then I do not get how is that different from var declaration and how functions get proper i value. To make it even more clear, lets say that let is bound to one new scope which is created by the for loop and var declaration is hoisted to the global scope in this case but thats still one scope to be working with.
Can anyone share some light on this topic?