为何调用Map.prototype.forEach会返回undefined?文档疑问解析
Map.prototype.forEach return undefined, and what does that mean exactly? Hey there! Great question—this is a super common point of confusion when first diving into Map objects, especially if you’re used to array methods that return useful values (like map or filter). Let’s break this down clearly:
1. Why does Map.prototype.forEach return undefined?
The short answer: it’s intentional by design. The core purpose of forEach (whether on Maps or Arrays) is to run a "side effect" for every entry in the collection—think logging values, updating external variables, or modifying elements in place. It’s not built to generate or return a new value or collection.
JavaScript’s specification explicitly defines Map.prototype.forEach to return undefined, no matter what your callback function returns. The callback’s return value is completely ignored by the method itself.
2. What does "returns undefined" actually mean?
When docs state this method returns undefined, it boils down to two key takeaways:
- No matter what logic you write inside your
forEachcallback, callingmyMap.forEach(...)will never hand you back any meaningful value—its return is always the primitiveundefined. - You can’t chain other methods onto
forEachlike you can with array methods that return values (e.g., you can’t domyMap.forEach(...).filter(...)becauseforEachgives you nothing to chain off of).
Example to see this in action
Let’s run through a quick code snippet to make it concrete:
const bookMap = new Map([ ['The Hobbit', 'J.R.R. Tolkien'], ['1984', 'George Orwell'] ]); // Try to capture the return value of forEach const result = bookMap.forEach((author, title) => { console.log(`${title} by ${author}`); return `${author}: ${title}`; // This return value is totally ignored! }); console.log(result); // Output: undefined
If you need a transformed collection...
If you want to create a new Map (or array) based on your original Map, forEach isn’t the right tool. Instead, you can manually collect results in an array, then convert it to a new Map:
const bookMap = new Map([['The Hobbit', 'J.R.R. Tolkien'], ['1984', 'George Orwell']]); const reversedEntries = []; bookMap.forEach((author, title) => { reversedEntries.push([author, title]); }); const authorToBookMap = new Map(reversedEntries); console.log(authorToBookMap); // Map(2) { 'J.R.R. Tolkien' => 'The Hobbit', 'George Orwell' => '1984' }
Wrap-up
Think of forEach as a "do this for every item" tool, not a "give me a new set of items" tool. Its undefined return value is just JavaScript’s way of saying: "I executed the logic you asked for each entry, but I don’t have anything to hand back to you."
内容的提问来源于stack exchange,提问作者Xinyi Li

