3

As the title suggests, is it safe to iterate over the new Set & Map types and delete entries during the iteration ?

In Java, for instance, this would cause ConcurrentModificationExceptions.

I was not able to find anything about this issue in the spec. So I guess it's allowed ??

Kr0e
  • 2,149
  • 2
  • 24
  • 40

1 Answers1

2

Quoting MapIterator object's next() section,

  1. Let entries be the List that is the value of the [[MapData]] internal slot of m.

  2. Repeat while index is less than the total number of elements of entries. The number of elements must be redetermined each time this method is evaluated.

... ...

  1. Set the [[Map]] internal slot of O to undefined.
  2. Return CreateIterResultObject(undefined, true).

Similarly from SetIterator object's next() section,

  1. Let entries be the List that is the value of the [[SetData]] internal slot of s.
  2. Repeat while index is less than the total number of elements of entries. The number of elements must be redetermined each time this method is evaluated.

... ...

  1. Set the [[IteratedSet]] internal slot of O to undefined.
  2. Return CreateIterResultObject(undefined, true).

Since the values are re-evaluated everytime next() is called, if the current pointer (index) is greater than the length of the entries, then it doesn't throw an error, instead returns undefined.


But, generally, avoid modifying the containers while iterating the same.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Notice though that the *number of entries* doesn't decrease. They just get set to `empty`. So it basically just says that new elements do have to get iterated. – Bergi Sep 04 '15 at 12:43