JavaScript Map forEach() Method
Below is the example of Map.forEach() Method
Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!
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)=>{ document.write(values,keys+"<br>") })</script> |
Output:
1a 2b 3c
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.
Code for the above method is provided below:
Program 1:
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 document.write(mp+ "<br>"); mp.forEach((values,keys)=>{ document.write("values: ",values+ ", keys: ",keys+ "<br>") })</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
Program 2:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><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 document.log(mp); let ul=document.querySelector("ul"); mp.forEach((values,keys)=>{ ul.innerHTML+=ul.innerHTML="<li>"+keys+" =>"+values+"</li>" }) </script></body></html> |
Output:
Browsers Supported:
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Internet Explorer
- Safari
- Opera


