Re:Go: Redefining For Loop Variable Semantics
by throw_m239339 on Tuesday October 11, 2022 @09:24AM
(#33163057)
This is mostly why Ecmascript introduced lexical scoping (a bit similar to "block" scoping) with "let" back int ES 5 I believe, because var used the function scope and anymore would run into weird isues whenever they did this:
for (var i = 0 ; i < 10 ; i ++ ){
someElement.addEventListener('click',function(){
console.log(i);
})
}
i would always be equal to 9. With let instead of var, i is properly scoped and the executed script display each increment correctly.
The solution before let was to introduce a closure in the for statement body
for (var i = 0 ; i < 10 ; i ++ ){
(function(i){
someElement.addEventListener('click',function(){
console.log(i);
}))(i)
}
in order to capture i value. let can also easily isolate the scope of a variable so that it doesn't popule the global scope
{
let foo = "bar";
var baz = "qix";
}
// foo is undefined here, while baz is defined.
which removes the need for self invoking functions.
The solution before let was to introduce a closure in the for statement body
in order to capture i value. let can also easily isolate the scope of a variable so that it doesn't popule the global scope which removes the need for self invoking functions.