JavaScript · The language round
How do map, filter and reduce work?
Short answer
map transforms every item, filter keeps items that pass a test, and reduce folds the array into a single value. They return new arrays or a final value and do not mutate the source.
These three methods cover most array transformations. The important distinction is the shape of the result: transform each item, select some items, or combine everything into one value.
const orders = [
{ id: 1, total: 120, paid: true },
{ id: 2, total: 80, paid: false },
{ id: 3, total: 200, paid: true },
];
const totals = orders.map((order) => order.total);
const paid = orders.filter((order) => order.paid);
const revenue = paid.reduce((sum, order) => sum + order.total, 0);
console.log(totals); // [120, 80, 200]
console.log(revenue); // 320Choosing the right method
mapwhen every input produces exactly one outputfilterwhen you only need the items that satisfy a predicatereducewhen the result is one value: a sum, a lookup table, a grouped object or a flattened arrayforEachwhen you only need side effects and do not need a returned array
reduce is the most flexible and the easiest to overuse. If a chain of map and filter is clearer, keep it. Reach for reduce when the accumulator genuinely represents the result.
const grouped = orders.reduce((groups, order) => {
const key = order.paid ? "paid" : "unpaid";
(groups[key] ??= []).push(order);
return groups;
}, {});reduce unless you are certain the array is non-empty. Calling it on an empty array without an initial value throws.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if you call `reduce` on an empty array without an initial value?
- 2When would you use `forEach` instead of `map`?
- 3Can you chain `map` and `filter`?
- 4Does `map` mutate the original array?
Say it in the interview
map transforms every element and returns a new array of the same length. filter returns a new array containing only elements that pass a predicate. reduce folds the array into one value using an accumulator, which can be a number, object, or another array. None of them mutate the original. I use reduce when the result is genuinely a single value and prefer map and filter when they make the intent clearer.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.