Map.forEach()
The Map.forEach() method in JavaScript executes a provided callback function once for each key-value pair in a Map object, in insertion order.
Syntax
</>
Copy
map.forEach(callbackFn)
map.forEach(callbackFn, thisArg)
Parameters
| Parameter | Description |
|---|---|
callbackFn | A function executed for each element in the Map. It receives three arguments: value, key, and the Map object. |
thisArg | (Optional) Value to use as this when executing callbackFn. |
Return Value
The forEach() method does not return a value; it simply executes the callbackFn for each key-value pair in the Map.
Examples
1. Iterating Over a Map
This example demonstrates how forEach() iterates over key-value pairs in a Map.
</>
Copy
const fruits = new Map([
["apple", 5],
["banana", 2],
["cherry", 7]
]);
fruits.forEach((quantity, fruit) => {
console.log(`Fruit: ${fruit}, Quantity: ${quantity}`);
});
Output
Fruit: apple, Quantity: 5
Fruit: banana, Quantity: 2
Fruit: cherry, Quantity: 7
forEach()iterates over each entry infruits, executing the callback function.- The callback receives the
quantityas the first argument and thefruitas the second argument.
2. Using thisArg in forEach()
You can pass a custom this context using the optional thisArg parameter.
</>
Copy
const carPrices = new Map([
["Tesla", 50000],
["BMW", 55000],
["Audi", 60000]
]);
const priceFormatter = {
currency: "USD",
displayPrice(price, car) {
console.log(`${car}: ${price} ${this.currency}`);
}
};
carPrices.forEach(priceFormatter.displayPrice, priceFormatter);
Output
Tesla: 50000 USD
BMW: 55000 USD
Audi: 60000 USD
- The
thisArgparameter ensures thatthis.currencyrefers topriceFormatter.currency. - Without
thisArg,thiswould beundefinedinstrict modeorwindowin non-strict mode.
3. Accessing the Entire Map
The third argument of the callback function gives access to the entire Map object.
</>
Copy
const countries = new Map([
["USA", "Washington, D.C."],
["France", "Paris"],
["Japan", "Tokyo"]
]);
countries.forEach((capital, country, map) => {
console.log(`Country: ${country}, Capital: ${capital}`);
console.log("Total countries in map:", map.size);
});
Output
Country: USA, Capital: Washington, D.C.
Total countries in map: 3
Country: France, Capital: Paris
Total countries in map: 3
Country: Japan, Capital: Tokyo
Total countries in map: 3
The map parameter provides access to the entire Map object, allowing additional operations.
