AppDividend
Latest Code Tutorials

Javascript Map forEach() Method with Example

0

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.

  1. callback: This is a callback function that executes on each function call.
  2. value: This is the value for each iteration.
  3. key: This is the key to reach iteration.
  4. 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: 

  1. Google Chrome
  2. Microsoft Edge
  3. Mozilla Firefox
  4. Internet Explorer
  5. Safari
  6. Opera

That is it for the JavaScript map forEach() method.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.