JavaScript Map forEach() Method Tutorial

In this section, we will learn what the forEach() method is and how to use it in JavaScript.

What is JavaScript Map forEach() Method? (Iterate a Map in JavaScript)

We use the `forEach()` method when we want to run a set of instructions for every entry (key-value) of the target map object.

The method takes one argument and that is a reference to a function, which is basically a callback function and that will be executed for each entry of the target map object.

JavaScript Map forEach() Method Syntax:

map.forEach(callback);

forEach() Function Parameters:

The method takes one argument and that is a reference to a function, which is basically a callback function and that will be executed for each entry of the target map object.

Note: it’s the body of the reference function that we define the instructions we want to be run for each entry.

When the `forEach()` method calls the reference function, it will pass 3 arguments to the function:

  • The first argument is the `value` of each entry on the target map.

Note: the first time the `forEach()` method runs, it will pass the first value of the target map, the second time it runs, it will pass the second value and so on until the end of the map.

  • The second argument is the `key` of each entry on the target map.

Note: the first time the `forEach()` method runs, it will pass the first key of the target map, the second time it runs, it will pass the second key and so on until the end of the map.

  • The third argument is the reference to the map object in which we’re running the `forEach()` method on it.

forEach() Function Return Value:

The return value of this method is undefined.

Example: using Map forEach() method in JavaScript

const map = new Map();
map.set("John","222-22222222");
map.set(22 , 2000);
map.set(true, false); 
map.set("Jack", "333-3234232");

function iterate(value, key, myMap){
  console.log(`The current key is: ${key} and the current value is: ${value}`)
  myMap.set(key, "******");
} 
map.forEach(iterate);
for (const value of map.values()){
  console.log(value);
}  

Output:

The current key is: John and the current value is: 222-22222222

The current key is: 22 and the current value is: 2000

The current key is: true and the current value is: false

The current key is: Jack and the current value is: 333-3234232

******

******

******

******

Inside the body of the `iterate` function, we’ve used the third argument, which is the target map, and changed the value for all the elements in this map.

So when we ran the `for-of` statement, you can see the values of all keys are changed to `******`.

Leave a Reply