Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created February 3, 2015 19:05
Show Gist options
  • Save benjamingr/36d25d7ae8bcaaa82a23 to your computer and use it in GitHub Desktop.
Save benjamingr/36d25d7ae8bcaaa82a23 to your computer and use it in GitHub Desktop.

Yes, it is perfectly fine to add elements and remove elements to a set while iterating it. This use case was considered and is supported in ECMAScript 2015 (ES6).

Here is the relevant part of the specification from %SetIteratorPrototype%.next:

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.

So the spec mandates that the length is re-evaluated at each turn so that items added during iteration will not be skipped.

Here is a short code snippet that demonstrates this ability

var set = new Set([1]);
for(let item of set){
   if(item < 10) set.add(item+1);
   console.log(item);
}

Which logs the numbers 1 to 10. Here is a version not using for... of you can run in your browser today:

var set = new Set([1]);
for (var _i = set[Symbol.iterator](), next; !(next = _i.next()).done;) {
   var item = next.value;
   if (item < 10) set.add(item + 1);
   document.body.innerHTML += " " + item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment