• JavaScript Video Tutorials

JavaScript - Map.forEach() Method



In JavaScript, the forEach() method is available on the Map object. It takes a callback function as a parameter. It executes once for each key-value pair in the Map object, in insertion order. This method does not return anything (i.e., it returns undefined), and it does not modify the Map object on which it is called.

This method is compatible on almost every browser such as Chrome, Edge, Firefox, Opera, and Safari.

Syntax

Following is the syntax of JavaScript Map.forEach() method −

forEach(callbackFn, thisArg)

Parameters

This method accepts two parameters. The same is described below −

  • callbackFn − A function that is called once for each element in the array. This function takes three parameters. Here's the description for each parameter −

    • element − The current element being processed.

    • index − The index of the current element.

    • array − The array forEach was called upon.

  • thisArg (optional) − This is an optional parameter that allows you to specify the value of this within the callbackFn.

Return value

This method returns nothing (i.e. "undefined").

Examples

Example 1

In this example, we are using the JavaScript forEach() method to iterate over each key-value pair in the Map object and print them −

<html>
<body>
   <script>
      const map = new Map([
         [1, 'apple'],
         [2, 'banana'],
         [3, 'cherry']
      ]);
      map.forEach((value, key) => {
         document.write(`${key}: ${value}`, "<br>");
      });
   </script>
</body>
</html>

If we execute the above program, it returns all the key-value pairs of the Map object.

Example 2

In this example, we are using the forEach() method to modify each "value" in the Map object to upperacase.

<html>
<body>
   <script>
      const myMap = new Map([
         [1, 'apple'],
         [2, 'banana'],
         [3, 'cherry']
      ]);
      myMap.forEach((value, key, map) => {
         map.set(key, value.toUpperCase());
      });
      document.write(myMap.get(1), "<br>");
      document.write(myMap.get(2), "<br>");
      document.write(myMap.get(3));
   </script>
</body>
</html>

After executing the above program, all the "values" in the Map object will be modified to uppercase.

Example 3

In the example below, we are using forEach() method to iterate over each key-value pair in the Map object and push them into an array called "keyValueArray".

<html>
<body>
   <script>
      const myMap = new Map([
         [1, 'apple'],
         [2, 'banana'],
         [3, 'cherry']
      ]);
   
      const keyValueArray = [];
      myMap.forEach((value, key) => {
         keyValueArray.push([key, value]);
      });
      document.write(keyValueArray); 
      
      // Output: [[1, 'apple'], [2, 'banana'], [3, 'cherry']]
   </script>
</body>
</html>

If we execute the above program, the elements in the Map object will be pushed into an empty array.

Advertisements