Javascript Map forEach() Method with Example
The forEach() is an inbuilt JavaScript function that executes a provided function once per every key/value pair in the Map object, in insertion order.
JavaScript Map forEach
The JavaScript map forEach() method executes the specified function once for each key/value pair in the Map object. The forEach function executes the provided callback once for each key of the map, which exists. It is not invoked for keys that have been deleted.
However, it is executed for values that are present but have the value undefined.
Syntax
map.forEach(callback, value, key, thisArg)
Parameters
The forEach() method accepts four parameters, as mentioned above, and described below.
- callback: This is a callback 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.
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 its 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 in the case when it was deleted and re-added before 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
Write the following code inside an app.js file.
// app.js 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, first, we created a Map and then insert the values in the map using the set() method.
Then using the forEach() method, we iterate the map and log the key and value one by one.
Browsers Supported:
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Internet Explorer
- Safari
- Opera
That is it for the JavaScript map forEach() method.