7

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?

Matthew
  • 4,149
  • 2
  • 26
  • 53
  • "Is there anyway to use let for supported browsers, but have some kind of fallback for other browsers" -- [Babel](https://babeljs.io) (or similar) is likely what you're looking for. – Whymarrh Jan 28 '16 at 17:37
  • no, there's no fallback. if you run code using `let` on an older browser that has no idea about the new syntax, it's going to be a syntax error no matter what you do with it. – Marc B Jan 28 '16 at 17:37
  • I think if you not use Babel (or similar) then you continue with **var** keyword because all low version browser not support **es6(let...)** – Sandeep Jan 28 '16 at 17:40
  • "*This seems totally crazy to me since it pollutes the namespace in an unintuitive way.*" - well you shouldn't use the global namespace too much anyway :-) Function-scoped variables are reasonable, and there are cases where you even *need* the counter variable after the loop - but yes, if you personally fine it unintuitive there is nothing holding you back from using `const` and `let` everywhere. – Bergi Jan 28 '16 at 18:16

1 Answers1

1

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.

Naftali
  • 144,921
  • 39
  • 244
  • 303