JavaScript Map forEach

JavaScript Map.forEach() is used to execute a given function for each of the key-value pair in this Map.

Syntax

The syntax to call forEach() method on a Map map1 is

map1.forEach (function(value, key) {
    //code
})

Examples

In the following example, we take a Map with keys 'a', 'b', and 'c'. We shall loop through these key-value pairs using forEach() 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 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 use Map.forEach() method in JavaScript, with examples.