forEach on Maps
You'll learn how to use forEach() to iterate over Map entries with a convenient callback function.
What is forEach on Maps?
Just like arrays, Maps have a forEach() method that lets you execute a function for each key-value pair. It's an alternative to for...of loops when you want a more functional style or need to perform side effects for each entry.
How forEach Works with Maps
The syntax looks familiar, but the parameter order is different from arrays:
const users = new Map([
['alice', { age: 25 }],
['bob', { age: 30 }],
['charlie', { age: 35 }]
]);
users.forEach((value, key, map) => {
console.log(`${key}: ${value.age} years old`);
});
// alice: 25 years old
// bob: 30 years old
// charlie: 35 years old
Notice the callback receives value first, then key — opposite of what you might expect! This matches array's forEach(value, index) pattern, but can be confusing.
The Optional Third Parameter
The third parameter is the Map itself, useful when you need to reference the original Map inside the callback:
const scores = new Map([
['Alice', 85],
['Bob', 92]
]);
scores.forEach((score, name, originalMap) => {
if (score > 90) {
console.log(`${name} gets an A! (Map size: ${originalMap.size})`);
}
});
// Bob gets an A! (Map size: 2)
When to Use forEach
Use forEach() when you're performing side effects (logging, updating DOM, calling APIs) rather than transforming data. If you need to build a new collection, a for...of loop might be clearer.
Key Takeaway: Maps support forEach() with callbacks that receive (value, key, map) — remember that value comes before key, unlike when destructuring entries!