Map.prototype.forEach()
map.forEach(callbackFn, thisArg) Returns:
undefined · Updated March 13, 2026 · Map and Set map foreach iteration
The forEach() method executes a provided function once for each key-value pair in the Map. The callback receives the value, key, and the Map itself as arguments.
Syntax
map.forEach(callbackFn, thisArg)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callbackFn | function | — | Function called for each key-value pair |
value | any | — | The current value |
key | any | — | The current key |
map | Map | — | The Map being iterated |
thisArg | any | undefined | Value to use as this |
Examples
Basic usage
const prices = new Map([
["apple", 1.5],
["banana", 0.75],
["orange", 2.0]
]);
prices.forEach((value, key) => {
console.log(`${key}: $${value}`);
});
// apple: $1.5
// banana: $0.75
// orange: $2.0
Using thisArg
const multiplier = {
factor: 2
};
const nums = new Map([["a", 1], ["b", 2], ["c", 3]]);
nums.forEach(function(value, key) {
console.log(`${key}: ${value} x ${this.factor} = ${value * this.factor}`);
}, multiplier);
// a: 1 x 2 = 2
// b: 2 x 2 = 4
// c: 3 x 2 = 6
Calculating totals
const orders = new Map([
["order1", 100],
["order2", 250],
["order3", 75]
]);
let total = 0;
orders.forEach((value) => {
total += value;
});
console.log(`Total: $${total}`); // Total: $425
Transforming to another structure
const users = new Map([
[1, { name: "Alice" }],
[2, { name: "Bob" }],
[3, { name: "Carol" }]
]);
const names = [Global_Objects::eval];
users.forEach((value, key) => {
names.push(`${key}: ${value.name}`);
});
console.log(names); // [1: Alice, 2: Bob, 3: Carol]
Filtering during iteration
const scores = new Map([
["player1", 95],
["player2", 82],
["player3", 78],
["player4", 91]
]);
const highScorers = [Global_Objects::eval];
scores.forEach((value, key) => {
if (value >= 90) {
highScorers.push(key);
}
});
console.log(highScorers); // [player1, player4]
Modifying values in place
const inventory = new Map([
["apples", 10],
["bananas", 5],
["oranges", 8]
]);
inventory.forEach((value, key, map) => {
map.set(key, value * 2);
});
console.log([...inventory]);
// [[apples, 20], [bananas, 10], [oranges, 16]]
With async operations
const apiCalls = new Map([
["user", "/api/user/1"],
["posts", "/api/posts"],
["comments", "/api/comments"]
]);
async function fetchAll() {
const results = new Map();
for (const [key, url] of apiCalls) {
// Simulated fetch
results.set(key, { url, status: "loaded" });
}
return results;
}
fetchAll().then(data => console.log([...data.entries()]));
Behavior Notes
- Iteration order follows insertion order
- No way to break out of forEach — use
for...ofinstead if you need early exit forEach()always returnsundefined