Why map and filter Beat forEach in JavaScript: Cleaner, Testable Code
Using map and filter instead of forEach when creating new arrays in JavaScript offers semantic separation, easier testing, better readability, and async compatibility, making code more functional and maintainable while avoiding side‑effects and unnecessary complexity.
Conclusion: When you need to use the whole or part of an array's elements to form a new array, it is recommended to use map and filter rather than forEach .
As a team leader and architect I see many projects with varied languages and skill levels. In JavaScript, a common anti‑pattern is using forEach to create a new array. The following simple example shows this pattern:
const kids = [];
people.forEach(person => {
if (person.age < 15) {
kids.push({ id: person.id, name: person.name });
}
});The code iterates over an array of people and pushes objects for those younger than 15 into kids. Although it works, the industry now favors functional array methods introduced in ES5.1: map and filter . These methods do not mutate the original array; they return a new array and accept a callback that is applied to each element.
map & filter
map : Calls the provided function on each element and stores the return values in a new array. filter : Calls the provided function on each element and includes the element in the new array only if the function returns true.
Another, less‑used method is reduce .
Simple usage example:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2); // [2, 4, 6, 8, 10]
const even = numbers.filter(number => number % 2 === 0); // [2, 4]Applying map and filter to the earlier scenario yields:
const kids = people
.filter(person => person.age < 15)
.map(person => ({ id: person.id, name: person.name }));Benefits over forEach:
Semantic separation : Filtering and transforming are distinct operations, each using a dedicated method.
Easier testing : Both map and filter are pure functions, making unit tests straightforward.
Readability : The intent of each step is clear, improving code comprehension.
Async compatibility : Unlike forEach, map can be combined with async/await when returning promises.
Note that map should not be used for side‑effects; it is meant to produce a new array, and the result should be utilized.
Summary
Using map and filter provides many advantages—semantic clarity, testability, readability, and better async handling—making them the preferred choice over forEach for creating new arrays in JavaScript.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Node Underground
No language is immortal—Node.js isn’t either—but thoughtful reflection is priceless. This underground community for Node.js enthusiasts was started by Taobao’s Front‑End Team (FED) to share our original insights and viewpoints from working with Node.js. Follow us. BTW, we’re hiring.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
