How to loop through set - JavaScript

Mo Ibra

Mo Ibra

Dec 22, 2022

In this article we will learn how to loop through set.

It is very common to loop through set in JavaScript.


Problem

Now we have a problem, which is that we want to loop over the set.

Let's imagine we have a set like this:

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

And we want to iterate over this set.

How to solve this problem

As we said before, there is more than one solution to solve this problem:

  • Using forEach
  • Using for ... of

Iterate over set using forEach

We can use forEach to iterate over set elements.

Example

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

// Iterate using `forEach`
set.forEach(ele => {
    console.log(ele);
});

Output

1
2
3

The forEach() method executes a provided function once for each array element.


Iterate over set using for .. of

We can use for .. of to iterate over set elements as well.

Example

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

// Iterate using `for .. of`
for (let value of set) {
    console.log(value);
}

Output

1
2
3

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: