4 ms·
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 sc
by throw_m239339 4y ago
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 developers would run into issues 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.