Categories
JavaScript Answers

How to Iterate Over JavaScript Set Elements?

Spread the love

To iterate over JavaScript set elements, we can use the for-of loop or the JavaScript set’s forEach method.

For instance, to iterate over a set with a for-of loop, we can write:

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

for (const el of set) {
  console.log(el)
}

We create the set set with the Set constructor with an array passed into it.

Then we use the for-of loop below that to loop through the items of set .

And so we should see 1, 2, and 3 logged.

To use the forEach method, we can write:

const set = new Set([1, 2, 3]);
set.forEach(el => console.log(el))

We call forEach with a callback with the el parameter logged in it.

And so we get the same result as before.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.