JavaScript 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: In this example, The forEach
method is used to log each key-value pair to the console.
// 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)
}) |
Output:
1a
2b
3c
Example 2: In this example, the forEach
method is employed to iterate through the map, printing each key-value pair to the console in the format “values: [value], keys: [key]”.
// 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)
}) |
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.
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); // logging concatenated keys and values mp.forEach((value, key) => { console.log(key+ ": " + value);
}); |
Map(6) { 'a' => 65, 'b' => 66, 'c' => 67, 'd' => 68, 'e' => 69, 'f' => 70 } a: 65 b: 66 c: 67 d: 68 e: 69 f: 70
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