JavaScript – Add an Element to Set

To add an element to a Set in JavaScript, call add() method on this Set and pass the element as argument. If the element is not preset in the Set already, then the element is added to the Set, else, Set remains unchanged.

Syntax

The syntax to add an element e to the Set set1 is

</>
Copy
set1.add(e)

Examples

In the following example, we create an empty Set, and add elements to this Set using add() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new 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>

If the element is already present in the Set, then the Set remains unchanged.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(['apple', 'banana', 'orange']);
        set1.add('banana'); //add element that is already present

        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 add an element to a Set in JavaScript using add() method, with examples.