0

Sometimes I like to use this kind of pattern for flattening nested data (arrays, tree structures and the like)

const stuff = [1, [2, [3, 4]]];
let pile = [stuff];
for (let item of pile) {
    if (item instanceof Array) pile.push(...item);
    else console.log(item);
}

It occurred to me though that I'm just assuming that

for (let item of pile) { ...

is syntax candy for

for (let i = 0; i < pile.length; i++) { const item = pile[i]; ...

while it could also be syntax candy for

for (let i = 0, length = pile.length; i < length; i++) { const item = pile[i]; ...

Right now it works the way I expect but is it guaranteed to work or is it implementation specific?

enzo
  • 9,861
  • 3
  • 15
  • 38
user81993
  • 6,167
  • 6
  • 32
  • 64
  • Does this answer your question? [For-Of Loop vs. For Loop](https://stackoverflow.com/questions/60924958/for-of-loop-vs-for-loop) – enzo Aug 12 '21 at 03:25
  • For-of is NOT syntactic-sugar of the indexed version. There are iterators and generators involved: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators – Mario Vernari Aug 12 '21 at 03:29
  • @Phil the example code does exactly that, doesn't mean its guaranteed behavior however – user81993 Aug 12 '21 at 03:29

1 Answers1

0

From MDN:

In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

This suggests it is syntactic sugar for

for (let i = 0, length = pile.length; i < length; i++) { const item = pile[i]; ...

Or something that is similar to that.

gijswijs
  • 1,958
  • 19
  • 24