JavaScript Set Iterating Sets


You can use a simple for-of loop to iterate a Set:

const mySet = new Set([1, 2, 3]);

for (const value of mySet) {
  console.log(value); // logs 1, 2 and 3

When iterating over a set, it will always return values in the order they were first added to the set. For example:

const set = new Set([4, 5, 6])
set.add(5) //5 already exists in the set
Array.from(set) //[4, 5, 6, 10]

There's also a .forEach() method, similar to Array.prototype.forEach(). It has two parameters, callback, which will be executed for each element, and optional thisArg, which will be used as this when executing callback.

callback has three arguments. The first two arguments are both the current element of Set (for consistency with Array.prototype.forEach() and Map.prototype.forEach()) and the third argument is the Set itself.

mySet.forEach((value, value2, set) => console.log(value)); // logs 1, 2 and 3