JavaScript – Check if Set contains a Specific Element

To check if this Set contains a specific element in JavaScript, call has() method on this set and pass the element, to search for, as argument to it.

has() method returns a boolean value. The return value is true if the element is present in the set, else, false.

Syntax

The syntax to check if specific element e is present in a Set set1 using has() method is

</>
Copy
set1.has(e)

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 result = set1.has('banana');

        var displayOutput = 'Is the element present? ' + result;
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Now, let us check if a key ‘cherry’ is present in this set.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(['apple', 'banana', 'orange']);
        var result = set1.has('cherry');

        var displayOutput = 'Is the element present? ' + result;
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to check if a specific element is present in a Set in JavaScript using has() method, with examples.