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 ??

0

1 Answer 1

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.

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.