Javascript famously does not create a new scope for each loop in a for
loop. So for example this code:
for(var i=0;i<10;i++){
//some code
}
console.log(i); //prints 10 instead of ReferenceError!
i
is actually created as a variable in the same scope as everything outside the for loop. This seems totally crazy to me since it pollutes the namespace in an unintuitive way.
However, the latest ECMA specifications have added a let
keyword that scopes variables to the containing block:
for(let i=0;i<10;i++){
//some code
}
console.log(i); //gives ReferenceError 'i' is not defined
Assuming that compatibility is not an issue (let
is supported in IE11, firefox, chrome, at least with strict mode) should we now consider let
to be the standard, correct way to write a for loop? Or is there some reason to continue using var
?
Also, what is the best approach for compatibility? Is there anyway to use let
for supported browsers, but have some kind of fallback for other browsers, or are we stuck using var
until everyone upgrades their browsers?