Iterate over the Elements in a Set using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Iterate over the Elements in a Set #

Use the forEach() method to iterate over the elements in a Set. The forEach method takes a function that gets invoked once for each value in the Set object. The forEach method returns undefined.

index.js
const set1 = new Set(['one', 'two', 'three', 'four']); // ✅ ️ using forEach set1.forEach(element => { console.log(element); // 👉️ one, two, three, four });

We used the Set.forEach method to iterate over the elements in the Set.

The function we passed to the method gets called with 3 arguments:

  • the element value
  • the element key
  • the Set object
Note that there are no keys in a Set object and the parameter is added to be consistent with the forEach methods of Map objects and arrays.

The callback function gets invoked once for each element in the Set, even if it has a value of undefined.

However, the function doesn't get invoked for values that have already been deleted from the Set.

An alternative approach is to use a for...of loop.

Use a for...of loop to iterate over the elements in a Set. The for...of allows us to iterate over iterable objects like Sets, arrays and Maps. The loop assigns a variable that stores the current Set element on each iteration.

index.js
const set1 = new Set(['one', 'two', 'three', 'four']); // ✅ using for...of for (const element of set1) { console.log(element); // 👉️ one, two, three, four }

We used a for...of loop to iterate over a Set.

This might be your preferred approach if you have to use the break statement to exit a loop prematurely. The break statement is not supported in the forEach() method.

The for...of loop iterates only over an object's own properties, as opposed to the for...in loop which also iterates over inherited properties.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.