The forEach method of the JavaScript Map executes a designated function for each key/value pair within the Map object, performing the operation exactly once for every entry.
Syntax
The syntax for the forEach method is outlined as follows:
mapObj.forEach(callback[, thisArg])
Parameter
callback - It represents the function to execute.
value - This signifies the value that is regarded as this when the callback function is executed.
JavaScript Map forEach method example
In this section, we will explore the forEach method by examining a range of examples.
Example 1
Let's examine an example that demonstrates how to retrieve values from a Map object.
<script>
var map = new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
document.writeln("Fetching values :"+"<br>");
function display(values)
{
document.writeln(values+"<br>");
}
map.forEach(display);
</script>
Output:
jQuery
AngularJS
Bootstrap
Example 2
Let’s examine an example of how to retrieve both keys and values from a Map object.
<script>
var map = new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
document.writeln("Fetching values and keys :"+"<br>");
function display(values,key)
{
document.writeln(values+" "+key+"<br>");
}
map.forEach(display);
</script>
Output:
Fetching values and keys :
jQuery 1
AngularJS 2
Bootstrap 3