2Minutes: Map vs. Filter vs. Reduce In JavaScript
Most developers use map, filter, and reduce every single day. Far fewer could explain, without opening the docs, why reaching for the wrong one turns three clean lines of code into a mess.
What Do They Actually Do?
Picture a basket of laundry. Map dyes every single shirt a new color — same number of shirts in the basket, just changed. Filter goes through the basket and pulls out only the dirty ones — fewer shirts, but the ones left are untouched. Reduce stuffs every shirt left into one duffel bag — no matter how many you started with, you walk away with exactly one thing.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const total = numbers.reduce((sum, n) => sum + n, 0); // 15map always returns a new array of the same length as the original. filter always returns an array too, but its length depends on how many items pass your test — it can shrink, it just never transforms the values themselves. reduce is the odd one out: it doesn’t have to return an array at all, it walks the whole list carrying an accumulator and hands you back whatever that accumulator ended up being.
The Trap: Reduce Can Fake Being Either One
Here’s the part that trips people up once they notice it: reduce is powerful enough to reimplement map and filter on its own.
const doubledWithReduce = numbers.reduce((acc, n) => {
acc.push(n * 2);
return acc;
}, []);This works, and produces the exact same array as numbers.map(n => n * 2). But just because reduce can do a job doesn’t mean it should — the moment another developer sees a bare .map() or .filter(), they instantly know the shape of the output. A .reduce() doing the same job forces them to read the whole callback to find out.
The takeaway for today is: map transforms, filter selects, reduce collapses — and the fact that reduce could technically replace the other two is exactly why you shouldn’t let it.
That’s 2Minutes Concept, see you in the next one!
Sources
https://www.freecodecamp.org/news/javascript-map-reduce-and-filter-explained-with-examples
https://www.geeksforgeeks.org/javascript/how-to-use-map-filter-and-reduce-in-javascript