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?
source share