JavaScript – Create a New Set

To create a new Set in JavaScript, use Set() constructor. Set() constructor accepts an array of elements, and creates a set from this array. If no argument is passed to Set() constructor, then it returns an empty set.

Syntax

The syntax to create a Set using Set() constructor is

</>
Copy
new Set() //empty set
new Set([element1, element2, ..., elementN]) //set from array

Examples

In the following example, we create an empty set, and add some elements to it.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(); //create empty set
        set1.add('apple'); //add element to set
        set1.add('banana'); //add element to set

        var displayOutput = '';
        set1.forEach (function(element) {
            displayOutput += element + '\n';
        });
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

In the following example, we create a set with by passing an array of elements as argument to Set() constructor.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        //create set from array
        var set1 = new Set(['apple', 'banana', 'cherry']);

        var output = '';
        set1.forEach (function(element) {
            output += element + '\n';
        });
        document.getElementById('output').innerHTML += output;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to create a Set in JavaScript using Set() constructor, with examples.