Search code examples
javascriptfor-loopscopeconstantsecmascript-6

ECMAScript 2015: const in for loops


Which of the two (or neither/ both) code fragments below should be working in a complete ECMAScript 2015 implementation:

for (const e of a)

for (const i = 0; i < a.length; i += 1)

From my understanding, the first example should work because e is initialized for each iteration. Shouldn't this also be the case for i in the second version?

I'm confused because existing implementations (Babel, IE, Firefox, Chrome, ESLint) do not seem to be consistent and have a complete implementation of const, with various behaviours of the two loop variants; I'm also not able to find a concrete point in the standard, so that would be much appreciated.


Solution

  • The following for-of loop works:

    for (const e of a)
    

    The ES6 specification describes this as:

    ForDeclaration : LetOrConst ForBinding

    http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for-of-statements-static-semantics-boundnames

    The imperative for loop will not work:

    for (const i = 0; i < a.length; i += 1)
    

    This is because the declaration is only evaluated once before the loop body is executed.

    http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-statement-runtime-semantics-labelledevaluation