While x is not a constant, how the following code runs without any errors?
for (const x of [1,2,3]){
console.log(x);
}
It works on compliant browsers like Chrome because they create a new, different, constant variable at each iteration:
var arr = [];
for (const x of [1,2,3])
arr.push(() => x);
arr.map(f => f()); // [1,2,3] on Chrome
Some non-compliant browsers reuse the same variable instead:
var arr = [];
for (let x of [1,2,3])
arr.push(() => x);
arr.map(f => f()); // [3,3,3] on non-compliant browsers
Therefore, they throw an error if in the example above you use const.
Runtime Semantics: ForIn/OfBodyEvaluation says:
- Repeat
- Else
- Assert: lhsKind is lexicalBinding.
- Assert: lhs is a ForDeclaration.
- Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
- Perform BindingInstantiation for lhs passing iterationEnv as the argument.
So each iteration should create a new binding. Chrome is correct.
SyntaxError: invalid for/in left-hand sideon Firefoxconsttovar.