How to Use the Map Iterator for Each in JavaScript?

Estimated read time 1 min read

The Map object in JavaScript provides a forEach method that you can use to iterate over its elements and perform operations on each key-value pair. Here’s an example:

let map = new Map([["A", 1], ["B", 2], ["C", 3]]);

map.forEach(function(value, key, map) {
  console.log(key + ": " + value);

// Output:
// A: 1
// B: 2
// C: 3

In the example above, we created a Map object and added three key-value pairs to it. Then, we used the forEach method to iterate over the elements in the map and log each key-value pair to the console.

The forEach method takes a callback function as an argument, which is called for each key-value pair in the map. The callback function takes three arguments: the value of the current element, the key of the current element, and the map being traversed.

You can use the forEach method to perform any operation you want on each element of the map. Just replace the function passed to the forEach method with the desired operation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply