JavaScript – Get Value for Specific Key in Map

To get value for a specific key in Map in JavaScript, call get() method on this Map and pass the specific key as argument. get() method returns the corresponding value for given key, if present. If the specified key is not present, then get() returns undefined.

Syntax

The syntax to get the value for a specific key in a Map map using get) method is

</>
Copy
map.get(key)

Examples

In the following example, we get the value for key 'a' using get() method.

index.html

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

        var displayOutput = 'Value for the specified key is ' + value + '.';
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Now, let us try to get the value for a key that is not present.

index.html

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

        var displayOutput = 'Value for the specified key is ' + value + '.';
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to get the value for a specific key in a Map in JavaScript using get() method, with examples.