What is the Map.forEach() method in JavaScript?

The forEach() method of the Map object executes the provided function for each entry (key-value pair) of the map.

Syntax

mapObj.forEach(callbackFn(value, key, map){}, thisArg);

Arguments

  1. callbackFn

    The forEach method takes a function as the first argument. The passed function will be executed for each key/value pair. The argument of the function can be:

    • value – The value of the currently iterating entry.
    • key – The key of the currently iterating entry.
    • map – The original map object.
  2. thisArg – The value of this inside the passed callback function. This is an optional argument.

Example

let markMap = new Map();
markMap.set("Ram", 30);
markMap.set("Raj", 50);
markMap.set("Randy", 22);
markMap.set("Rahul", 100);
markMap.forEach((val, key)=>{
console.log("The name is ", key);
console.log("The mark is ", val);
console.log("Status ", val>30 ? "PASS" : "FAIL");
console.log("-----------------\n");
});
  • We create a map object to store the user mark.

  • Then, we use the forEach method to loop through each key-value pair of the markMap. Inside the callback function, we print the name, mark, and pass or fail status.

Free Resources