Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  3] [ 3]  / answers: 1 / hits: 58300  / 9 Years ago, thu, august 13, 2015, 12:00:00

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.


More From » for-loop

 Answers
91

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


[#65426] Tuesday, August 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;