Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Map forEach() Method

Improve Article
Save Article
  • Last Updated : 09 Jan, 2023
Improve Article
Save Article

The Map.forEach method is used to loop over the map with the given function and executes the given function over each key-value pair.

Syntax:

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

Parameters: This method accepts four parameters as mentioned above and described below:

  • callback: This is the function that executes on each function call.
  • value: This is the value for each iteration.
  • key: This is the key to reach iteration.
  • thisArg: This is the value to use as this when executing callback.

Returns: It returns the undefined value.

Example 1: Below is an example of the Map.forEach() Method

Javascript




<script>
    // Creating a map using Map object
    let mp=new Map()
     
    // Adding values to the map
    mp.set("a",1);
    mp.set("b",2);
    mp.set("c",3);
     
    // Logging map object to console
    mp.forEach((values,keys)=>{
      console.log(values,keys)
    })
</script>

Output: 

1a
2b
3c

Example 2: This example shows the basic use of the Javascript Map.forEach() method.

HTML




<script>
    // Creating a map using Map object
    let mp=new Map()
     
    // Adding values to the map
    mp.set("a",65);
    mp.set("b",66);
    mp.set("c",67);
    mp.set("d",68);
    mp.set("e",69);
    mp.set("f",70);
     
    // Logging map object
    console.log(mp);
    mp.forEach((values,keys)=>{
      console.log("values: ",values+
                     ", keys: ",keys)
    })
</script>

Output: 

[object Map]
values: 65, keys: a
values: 66, keys: b
values: 67, keys: c
values: 68, keys: d
values: 69, keys: e
values: 70, keys: f

Example 3: This example shows the basic use of the Javascript Map.forEach() method.

HTML




<ul class="list">
</ul>
<script>
    // Creating a map using Map object
    let mp=new Map()
    //adding values to the map
    mp.set("a",65);
    mp.set("b",66);
    mp.set("c",67);
    mp.set("d",68);
    mp.set("e",69);
    mp.set("f",70);
    //logging map object to console
    console.log(mp);
    let ul=document.querySelector("ul");
    mp.forEach((values,keys)=>{
      ul.innerHTML+=ul.innerHTML="<li>"+keys+" =>"+values+"</li>"
    })
</script>

Output:

JavaScript Map forEach() Method

We have a complete list of Javascript Map Methods, to check those please go through Javascript Map Complete Reference article.

Browsers Supported: 

  • Google Chrome 38 and above
  • Microsoft Edge 12 and above
  • Mozilla Firefox 25 and above
  • Internet Explorer 11 and above
  • Safari 8 and above
  • Opera 25 and above

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!