How to Iterate Over Elements of a JavaScript Set?

You can iterate over the elements of a JavaScript Set object in the following ways:

In addition to these, you can also convert the Set to an array, and iterate over it.

Using Set.prototype.forEach()

The Set.prototype.forEach() method allows you to iterate over the elements of a Set in insertion order and perform an action for each element.

For example:

// ES6+
const mySet = new Set();

mySet.add('foo');
mySet.add('bar');
mySet.add('baz');

mySet.forEach(function (value) {
  console.log(value); // 'foo' 'bar' 'baz'
});

As you can see in the example above, the Set.prototype.forEach() method takes a callback function as an argument, which is called for each element in the Set.

Using the Set.prototype.forEach() method can be useful in situations where you only need to perform a specific action for each element in the Set and do not need to use return, break or continue in the loop.

Using for...of Loop

The for...of loop allows you to iterate over the elements of an iterable object, such as a Set. The elements of the Set are visited in insertion order.

For example:

// ES6+
const mySet = new Set();

mySet.add('foo');
mySet.add('bar');
mySet.add('baz');

for (const item of mySet) {
  console.log(item); // 'foo' 'bar' 'baz'
}

In the example above, the loop iterates over the elements of the Set, and assigns each element to a variable (in this case, item), which you can then use in the loop's body.

Using a for...of loop can be useful in situations where you need to use return, break or continue in the loop.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.