4

While x is not a constant, how the following code runs without any errors?

for (const x of [1,2,3]){
console.log(x);
}
6
  • try doing x=x+1 inside the for let me go how it goes Commented Apr 18, 2016 at 1:39
  • In IE11 I do get an error when I run it: "Const must be initialised". Commented Apr 18, 2016 at 1:39
  • SyntaxError: invalid for/in left-hand side on Firefox Commented Apr 18, 2016 at 1:43
  • works fine here : jsbin.com/solisa/1/edit?js,console Commented Apr 18, 2016 at 1:44
  • 2
    @JordanHendrix You are using Babel, which converts const to var. Commented Apr 18, 2016 at 1:47

1 Answer 1

6

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:

  1. Repeat
    1. Else
      1. Assert: lhsKind is lexicalBinding.
      2. Assert: lhs is a ForDeclaration.
      3. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
      4. Perform BindingInstantiation for lhs passing iterationEnv as the argument.

So each iteration should create a new binding. Chrome is correct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.