Loop through a Set using Javascript

In JavaScript, you can loop through a Set using several methods. The most common approaches are using the forEach() method, for...of loop, or converting to an array.

Using forEach() Method

The forEach() method executes a provided function for each value in the Set:

const mySet = new Set([1, 2, 5, 8]);

mySet.forEach(value => {
    console.log(`Element is ${value}`);
});
Element is 1
Element is 2
Element is 5
Element is 8

Using for...of Loop

The for...of loop provides a cleaner syntax for iterating over Set values:

const mySet = new Set(['apple', 'banana', 'orange']);

for (const value of mySet) {
    console.log(`Fruit: ${value}`);
}
Fruit: apple
Fruit: banana
Fruit: orange

Using Array.from() with Array Methods

Convert the Set to an array to use array methods like map() or filter():

const mySet = new Set([10, 20, 30, 40]);

Array.from(mySet).forEach((value, index) => {
    console.log(`Index ${index}: ${value}`);
});
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40

Custom Implementation Example

Here's how you might implement a custom forEach function for a Set-like class:

class MySet {
    constructor() {
        this.container = {};
    }
    
    add(value) {
        this.container[value] = true;
    }
    
    forEach(callback) {
        for (let prop in this.container) {
            callback(prop);
        }
    }
}

const testSet = new MySet();
testSet.add(1);
testSet.add(2);
testSet.add(5);

testSet.forEach(elem => console.log(`Element is ${elem}`));
Element is 1
Element is 2
Element is 5

Comparison of Methods

Method Syntax Index Available? Use Case
forEach() Clean No Simple iteration
for...of Very clean No Modern loops, break/continue
Array.from() Verbose Yes Need array methods or index

Conclusion

Use for...of for simple iteration, forEach() for functional style, and Array.from() when you need array methods or indices. All native Set methods maintain insertion order.

Updated on: 2026-03-15T23:18:59+05:30

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements