Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always use `let` in for loops? [duplicate]

Tags:

javascript

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?

like image 297
Matthew Avatar asked Jan 28 '16 17:01

Matthew


People also ask

Should I use let or const in for loop?

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.

Why do we use let in for loop?

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.

What is the difference between VAR and let in for loop?

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.

Can I use the same variable for multiple for loops?

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.


1 Answers

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.

like image 114
Naftali Avatar answered Oct 11 '22 12:10

Naftali