JavaScript Map forEach() Method

JavaScript map forEach() is a built-in method that executes the specified function once for each key/value pair in the Map object. It executes the provided callback once for each key of the existing map.


map.forEach(callback, value, key, thisArg)


The forEach() method accepts four parameters mentioned above and described below.

  1. callback: This is a callback function that executes each function call.
  2. value: This is the value for each iteration.
  3. key: This is the key to reaching iteration.
  4. thisArg: This is the value to use as this when executing callback.

If a thisArg argument is provided to forEach, it will be passed to the callback when invoked for use as its “this” value. Otherwise, the value undefined will be given for use as this value.

this” value ultimately observable by callback is defined according to the usual rules for determining the “this” seen by the function.

Each value is visited once, except when it was deleted and re-added before the forEach function has finished. The callback is not invoked for values removed before being visited. New values added before the forEach() function has finished will be visited.

Map forEach() method executes the callback function once for each element in the Map object. It does not return a value.

Return Value

The forEach() function returns the undefined value.

Example 1

let mp = new Map();

// Adding values to the map 
mp.set("First", "Krunal");
mp.set("Second", "Ankit");
mp.set("Third", "Rushabh");
mp.set("Fourth", "Dhaval");
mp.set("Fifth", "Niva");

mp.forEach((values, keys) => {
  console.log("values: ", values +
              ", keys: ", keys + "\n")


values: Krunal, keys: First

values: Ankit, keys: Second

values: Rushabh, keys: Third

values: Dhaval, keys: Fourth

values: Niva, keys: Fifth

In this example, we created a Map and then inserted the values in the map using the set() method.

Then using the forEach() method, we iterate the map and log the key and value individually.

Example 2

let myMap = new Map();

myMap.set("a", 1);
myMap.set("b", 2);
myMap.set("c", 3);

function showPair(value, key) {
   console.log(`key: ${key}, value: ${value}`);



key: a, value: 1
key: b, value: 2
key: c, value: 3

Browsers Supported

  1. Google Chrome
  2. Microsoft Edge
  3. Mozilla Firefox
  4. Internet Explorer
  5. Safari
  6. Opera

That is it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.