Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

foreach
map
javascript
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

foreach
map
javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring