JavaScript – Insert Key-Value Pair in Map

To insert a new key-value pair to a Map in JavaScript, call set() method on this Map and pass the key and value as arguments.

Syntax

The syntax to insert a new key-value pair into a Map map is

</>
Copy
map.set(key, value)

Examples

In the following example, we create an empty map, and insert some key-value pairs into it using set() method.

index.html

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

        var displayOutput = '';
        map1.forEach (function(value, key) {
            displayOutput += key + ' - ' + value + '\n';
        });
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

If the key already exists, then the value is updated with the new value.

index.html

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

        map1.set('a', 88);

        var displayOutput = '';
        map1.forEach (function(value, key) {
            displayOutput += key + ' - ' + value + '\n';
        });
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to insert a new key-value pair into a Map in JavaScript using set() method, with examples.