JavaScript Set forEach

JavaScript Set.forEach() is used to execute a given function for each of the element in this Set.

Syntax

The syntax to call forEach() method on a Set set1 is

set1.forEach (function(element) {
    //code
})

Examples

In the following example, we take a Set with three elements and use forEach() method to execute a function for each of these elements.

index.html

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

Conclusion

In this JavaScript Tutorial, we learned how to use Set.forEach() method in JavaScript, with examples.