Open In App

How to Iterate over the Elements of a Set in JavaScript ?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, you can iterate over the elements of a Set using various methods, such as the forEach() method, the for...of loop, or by converting the Set to an array and using array iteration methods.

  1. Using forEach() method:
    let mySet = new Set([1, 2, 3, 4, 5]);

    mySet.forEach(function(value) {
    console.log(value);
    });
  2. Using for...of loop:
    let mySet = new Set([1, 2, 3, 4, 5]);

    for (let value of mySet) {
    console.log(value);
    }
  3. Converting Set to Array and using array iteration methods:
    let mySet = new Set([1, 2, 3, 4, 5]);

    // Convert Set to an array using the spread operator
    let myArray = [...mySet];

    // Use array iteration methods on the array
    myArray.forEach(function(value) {
    console.log(value);
    });

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads