JavaScript Map forEach() Method
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
// Creating a map using Map objectlet mp = new Map()// Adding values to the mapmp.set("a", 1);mp.set("b", 2);mp.set("c", 3);// Logging map object to consolemp.forEach((values, keys) => { console.log(values, keys)}) |
Output:
1a 2b 3c
Example 2: This example shows the basic use of the Javascript Map.forEach() method.
Javascript
// Creating a map using Map objectlet mp = new Map()// Adding values to the mapmp.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 objectconsole.log(mp);mp.forEach((values, keys) => { console.log("values: ", values + ", keys: ", keys)}) |
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
<!DOCTYPE html><html lang="en"><body> <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></body></html> |
Output:
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


Please Login to comment...