JavaScript map forEach() is a built-in method that executes the specified function once for each key/value pair in the Map object. It executes the provided callback once for each key of the existing map.
Syntax
map.forEach(callback, value, key, thisArg)
Parameters
The forEach() method accepts four parameters mentioned above and described below.
- callback: This is a callback function that executes each function call.
- value: This is the value for each iteration.
- key: This is the key to reaching iteration.
- thisArg: This is the value to use as this when executing callback.
If a thisArg argument is provided to forEach, it will be passed to the callback when invoked for use as its “this” value. Otherwise, the value undefined will be given for use as this value.
“this” value ultimately observable by callback is defined according to the usual rules for determining the “this” seen by the function.
Each value is visited once, except when it was deleted and re-added before the forEach function has finished. The callback is not invoked for values removed before being visited. New values added before the forEach() function has finished will be visited.
Map forEach() method executes the callback function once for each element in the Map object. It does not return a value.
Return Value
The forEach() function returns the undefined value.
Example 1
let mp = new Map();
// Adding values to the map
mp.set("First", "Krunal");
mp.set("Second", "Ankit");
mp.set("Third", "Rushabh");
mp.set("Fourth", "Dhaval");
mp.set("Fifth", "Niva");
mp.forEach((values, keys) => {
console.log("values: ", values +
", keys: ", keys + "\n")
});
Output
values: Krunal, keys: First
values: Ankit, keys: Second
values: Rushabh, keys: Third
values: Dhaval, keys: Fourth
values: Niva, keys: Fifth
In this example, we created a Map and then inserted the values in the map using the set() method.
Then using the forEach() method, we iterate the map and log the key and value individually.
Example 2
let myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);
myMap.set("c", 3);
function showPair(value, key) {
console.log(`key: ${key}, value: ${value}`);
}
myMap.forEach(showPair);
Output
key: a, value: 1
key: b, value: 2
key: c, value: 3
Browsers Supported
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Internet Explorer
- Safari
- Opera
That is it.