Iterate over the Elements in a Set using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

banner

Photo by processingly

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 executed 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 value 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 keyword to exit a loop prematurely, as this is not supported when using 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee