map returns a new array with every element transformed, filter returns a new array with the elements that pass a test, and reduce folds the array into one value of any type. None of them mutates the array.
Frontend interview practice question
map vs filter vs reduce in JavaScript (Array Transformations)
Interview quick answer
Interview focus
This JavaScript interview question tests whether you can explain map vs filter vs reduce in JavaScript: when to use each, connect it to production trade-offs, and handle common follow-up questions.
- map vs filter vs reduce in JavaScript: when to use each explanation without falling back to memorized definitions
- Arrays and Array Methods reasoning, edge cases, and production failure modes
- How you would answer the most likely JavaScript interview follow-up
Use this JavaScript interview question to rehearse a quick answer, common mistake, follow-up, and production pitfall.
Full interview answer
map returns a new array of the same length with every element transformed by the callback. filter returns a new array, the same length or shorter, holding only the elements whose callback returned a truthy value. reduce walks the array once and returns a single value of any type, built up in an accumulator. None of the three changes the array it runs on, although a callback can still mutate the objects inside it. In interviews the follow-ups are about what each one returns, when to chain them, and when a single reduce pass is the better choice.
Aspect | map | filter | reduce |
|---|---|---|---|
Returns | A new array | A new array | One value of any type |
Result length | Same as the input | Same or shorter | Not an array unless you build one |
Callback returns | The new element | Truthy keeps the element, falsy drops it | The next accumulator |
Callback arguments |
|
|
|
Extra parameter |
|
|
|
Mutates the source array | No | No | No, unless the callback does |
Holes in sparse arrays | Skipped | Skipped | Skipped |
Typical use | Transform every item | Select a subset | Aggregate, group or index |
The trap interviewers probe | Using it as a filter leaves | It tests truthiness, not | No |
map vs filter: the same array, two results
map keeps the length and changes the values; filter keeps the values and changes the length. The classic mistake is using map to drop items, which leaves undefined holes in the result.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10] same length, new values
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4] shorter, same values
// Wrong: map cannot drop items
const wrong = numbers.map(n => (n % 2 === 0 ? n : undefined));
// [undefined, 2, undefined, 4, undefined]
// Right: filter first, then map
const evenSquares = numbers.filter(n => n % 2 === 0).map(n => n * n);
// [4, 16]
reduce: one value of any type
reduce calls the callback with an accumulator and the current element and keeps whatever the callback returns as the next accumulator. The result can be a number, an object, a Map, or another array. The pitfall is the second argument: without initialValue, the first element becomes the accumulator and the loop starts at the second, so an empty array has nothing to start from and throws.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 10
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false }
];
const byId = users.reduce((acc, user) => {
acc[user.id] = user;
return acc;
}, {});
// { 1: { id: 1, ... }, 2: { id: 2, ... } }
[].reduce((acc, n) => acc + n);
// TypeError: Reduce of empty array with no initial value
[].reduce((acc, n) => acc + n, 0);
// 0
Chain map and filter, or write one reduce?
Yes, you can chain them, and that is the normal way to select and then transform. The chain creates one intermediate array and reads like the sentence that describes it. A single reduce does the same work in one pass but hides the intent inside the callback, so reach for it when the result is one value, a grouping or an index, not as a general replacement.
// Chain: select, then transform (one intermediate array)
const activeNames = users
.filter(user => user.active)
.map(user => user.name);
// ['Alice']
// One pass with reduce: same result, more to read
const activeNames2 = users.reduce((acc, user) => {
if (user.active) acc.push(user.name);
return acc;
}, []);
The performance argument is weaker than it sounds. The chain visits the array twice and allocates one extra array; for a few thousand elements that costs microseconds, far below anything a user can notice. Measure in a hot path before trading readability for it, and both are linear, so the Big-O is the same either way. Practice the three on removing falsy values, summing numbers and flattening one level.
Mistakes interviewers look for
- Using
mapfor side effects such as logging or pushing into another array. That is aforEachjob;mapallocates a result nobody reads. - Using
mapto drop items. It cannot change the length; you getundefinedentries. Filter first. - A block body without
return:numbers.map(n => { n * 2; })gives an array ofundefined. The missing-return debug exercise is exactly this bug. - Mutating objects inside the callback.
mapgives you a new array, but the elements are the same object references, souser.active = falseinside the callback changes the original data too. Copy the object before changing it; see shallow vs deep copy. ['10', '10', '10'].map(parseInt)returns[10, NaN, 2], becausemappasses the index as the second argument andparseIntreads it as the radix. The map(parseInt) question walks through it.asynccallbacks.mapwith an async function returns an array of promises, so wrap it inPromise.all.filtercannot await at all: a promise is always truthy, so every element passes. Resolve the checks withmapandPromise.allfirst, then filter, or use afor...ofloop.- Forgetting
initialValueinreduce. Empty input throws, and a non-empty input starts with the first element as the accumulator, which breaks as soon as the elements and the result have different shapes. - Counting on holes. All three skip empty slots in sparse arrays, while a plain
forloop visits them asundefined, so the two can disagree on length-dependent results.
Related methods you will be asked about
The follow-up is usually about the neighbors, especially forEach; the forEach vs map answer covers that pair in depth.
Method | Returns | Use it when |
|---|---|---|
|
| You only want side effects and never need the result; it cannot break early. |
| The first matching element, or | You need one item, not the whole subset. |
| A boolean | You are asking whether any or all elements pass a test; both stop as soon as the answer is known. |
| A new array, flattened one level | Each element maps to zero, one or many results, such as splitting sentences into words. |
| Nothing, it is a statement | You need |
Interview follow-ups
Can you use map and filter together?
Yes, chaining is the idiomatic way to select and then transform: items.filter(test).map(transform). The chain creates one intermediate array; use a single reduce only when that allocation shows up in a measurement or when the result is not an array.
What is the difference between map, filter and reduce?
map transforms every element and returns an array of the same length. filter keeps the elements that pass a test and returns an array of the same length or shorter. reduce combines all elements into one value of any type through an accumulator.
What is the difference between map, forEach and filter?
forEach runs a callback for its side effects and returns undefined. map returns a new array of transformed values. filter returns a new array of the values that passed a test. Pick forEach when nobody needs a result, and never pick it when somebody does.
Does map change the original array?
No. map, filter and reduce never reassign or resize the array they run on. The elements are passed by reference, though, so mutating an object inside the callback changes the object the original array also holds.
What does reduce return on an empty array?
The initialValue, if you passed one. Without it, reduce throws a TypeError, because there is no element to use as the starting accumulator.
When should you use reduce instead of map and filter?
When the result is a single value, such as a sum, a count, a grouped object or an index by id, or when a measured hot path cannot afford the intermediate array. If the code reads as select then transform, keep the chain.
Still so complicated?
Picture an assembly line:
- map repaints every item and sends the same number of items on.
- filter pulls some items off the belt and sends the rest on unchanged.
- reduce packs whatever arrives into one box and hands you the box.
The line never touches the warehouse the items came from, unless a worker scribbles on an item instead of repainting a copy.
Summary
maptransforms each element,filterselects some elements, andreducecombines all elements into a single result of any type.mapkeeps the length,filterkeeps the values,reducekeeps whatever the accumulator says.- Chain
filterandmapto select and then transform; use onereducefor a single value, a grouping or an index. - None of them mutates the array, but callbacks can mutate the objects inside it; copy before changing.
- Always pass
initialValuetoreduce, wrap asyncmapcalls inPromise.all, and never usemapas a filter.
Use this as one explanation rep, then continue with the JavaScript interview questions cluster or a guided prep path.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.