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?
A for loop's control variable is normally not constant (since in the normal case you update it in the "update" clause of the for ; if you don't, for may be the wrong loop to use), so you normally use let with it.
According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block.
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
In your code, as you've shown it, it makes absolutely NO difference whatsoever whether you use the same variable name, or different names. It will not change functionality or memory usage at all. If any of the loops were nested, it would make a big difference, within the nested loops.
This is why projects like BabelJS were created for backward compat.
Thew "standard" is to try to use let
in those cases, if you want backwards compat you need to use babel or some other compiler that will bring your code up to es5 standards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With