JavaScript Iterate over Elements of a Set

To iterate over elements of a Set in JavaScript, call values() method on this set which returns an iterator and use for-of loop over this iterator.

Refer JavaScript For-of Loop.

Syntax

The syntax to get iterator for elements in the Set set1 using values() method is

set1.values()

We may use for-of loop as shown in the following to iterate over the elements of this iterator.

for (element of set1.values()) {
    //code
}

Examples

In the following example, we take a Set with initialised with three element. We shall check if the element 'banana' is present in this Set using has() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(['apple', 'banana', 'orange']);
        
        var displayOutput = '';
        for (element of set1.values()) {
            displayOutput += element + '\n';
        }
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to iterate over the elements of this Set in JavaScript using values() method and for-of loop, with examples.