Iterate Over Set in JavaScript


Sets are data structures that store unique values of any type without maintaining a particular elemental order and it prevents duplication. While working with Sets, developers frequently need to iterate over their elements to perform various operations or retrieve the values. More specifically, iterating over a Set in JavaScript involves accessing and processing each element stored within the Set.

This tutorial will describe different methods for iterating Sets in JavaScript.

How to Iterate Over the Elements of Set in JavaScript?

To iterate Sets, use the following JavaScript approaches:

  • forEach() method
  • for-of loop

Method 1: Iterate the Elements of Set in JavaScript Using the “forEach()” Method

Use the “forEach()” method or also known as the “forEach” loop, to iterate the elements of Sets in JavaScript. It allows the execution of the callback function for each element of the Set.

Syntax

Utilize the following syntax for iterating the Set using the forEach() method:

Set.forEach((element) => { 
// ..... 
});

Example

First, define a Set named “langSet” that contains programming languages:

const langSet = new Set(['HTML', 'CSS', 'JavaScript', 'Java']);

Call the forEach() method on the Set to iterate elements and display them on the console:

langSet.forEach((elem) => { 
console.log(elem); 
});

The output indicates that the elements of Set have been successfully iterated:

Method 2: Iterate the Elements of Set in JavaScript Using “for-of” Loop

Another way for iterating Set elements is to use the “for-of” loop. It is a convenient way to iterate over iterable objects, including Sets.

Syntax

The given syntax is used for iterating Set using the for-of loop:

for (const element of Set) { 
//.... 
}

Example

Use the for-of loop for iterating elements in the Set and display them on the console:

for (const elem of langSet) { 
console.log(elem); 
}

Output

We have compiled all the relevant information related to the iterating Set elements in JavaScript.

Conclusion

To iterate Sets, use JavaScript predefined approaches including the “forEach()” method or the “for-of” loop. Both approaches allow access and manipulation of the individual elements of a Set. The for-of loop gives additional flexibility and control to conduct custom actions within the loop body. On the other hand, the forEach() method provides a clear and straightforward approach to executing a provided function for each element in the Set. This tutorial described the approaches for iterating Sets in JavaScript.

Print Friendly, PDF & Email
Categories