Should we always use `let` in for loops?

Javascript does not famously 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 actually created as a variable in the same scope as everything outside the for loop. This seems completely crazy to me, as it is unintuitively polluting the namespace.

However, recent ECMA specifications have added the let keyword, which binds variables to the containing block:

 for(let i=0;i<10;i++){ //some code } console.log(i); //gives ReferenceError 'i' is not defined 

Assuming compatibility is not a problem ( let supported in IE11, firefox, chrome, at least in strict mode), should let now be considered a standard, correct way to write a for loop? Or is there some reason to continue using var ?

Also, what is the best fit for compatibility? Is it possible to use let for supported browsers, but have some kind of reserve for other browsers, or are we stuck with var until everyone updates their browsers?

+5
source share
1 answer

This is why projects such as BabelJS were created for backward compatibility.

Thew "standard" is to try to use let in these cases, if you want to use backward compatibility, you need to use babel or some other compiler that will bring your code to es5 standards.

+1
source

Source: https://habr.com/ru/post/1241744/


All Articles