JavaScript – Check if Map contains a Specific Key

To check if Map contains a specific key in JavaScript, call has() method on this map and pass the specific key as argument to it.

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

Syntax

The syntax to check if specific key key is present in a Map map using has() method is

</>
Copy
map.has(key)

Examples

In the following example, we take a Map with keys 'a', 'b', and 'c'. We shall check if the key 'b' is present in this Map using has() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var map1 = new Map([
            ['a', 10],
            ['b', 20],
            ['c', 30]
        ]);

        var result = map1.has('b');

        var displayOutput = 'Is the key present in Map? ' + result + '\n\n';
        document.getElementById('output').innerHTML += displayOutput;

</script>
</body>
</html>

Now, let us check if a key ‘x’ is present in this map.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var map1 = new Map([
            ['a', 10],
            ['b', 20],
            ['c', 30]
        ]);

        var result = map1.has('x');

        var displayOutput = 'Is the key present in Map? ' + result + '\n\n';
        document.getElementById('output').innerHTML += displayOutput;

</script>
</body>
</html>

Conclusion

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