Frontend interview practice question

map vs filter vs reduce in JavaScript (Array Transformations)

HighIntermediateJavascript

Interview quick answer

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.

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
Practice more JavaScript interview questions
Interview answer drill

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

element, index, array

element, index, array

accumulator, element, index, array

Extra parameter

thisArg (ignored by arrow functions)

thisArg (ignored by arrow functions)

initialValue

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 undefined entries

It tests truthiness, not === true

No initialValue on an empty array throws

map vs filter vs reduce at a glance

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.

JAVASCRIPT
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.

JAVASCRIPT
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.

JAVASCRIPT
// 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 map for side effects such as logging or pushing into another array. That is a forEach job; map allocates a result nobody reads.
  • Using map to drop items. It cannot change the length; you get undefined entries. Filter first.
  • A block body without return: numbers.map(n => { n * 2; }) gives an array of undefined. The missing-return debug exercise is exactly this bug.
  • Mutating objects inside the callback. map gives you a new array, but the elements are the same object references, so user.active = false inside 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], because map passes the index as the second argument and parseInt reads it as the radix. The map(parseInt) question walks through it.
  • async callbacks. map with an async function returns an array of promises, so wrap it in Promise.all. filter cannot await at all: a promise is always truthy, so every element passes. Resolve the checks with map and Promise.all first, then filter, or use a for...of loop.
  • Forgetting initialValue in reduce. 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 for loop visits them as undefined, 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

forEach

undefined

You only want side effects and never need the result; it cannot break early.

find

The first matching element, or undefined

You need one item, not the whole subset.

some / every

A boolean

You are asking whether any or all elements pass a test; both stop as soon as the answer is known.

flatMap

A new array, flattened one level

Each element maps to zero, one or many results, such as splitting sentences into words.

for...of

Nothing, it is a statement

You need break, continue or await inside the loop.

Neighbors of map, filter and reduce

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

  • map transforms each element, filter selects some elements, and reduce combines all elements into a single result of any type.
  • map keeps the length, filter keeps the values, reduce keeps whatever the accumulator says.
  • Chain filter and map to select and then transform; use one reduce for 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 initialValue to reduce, wrap async map calls in Promise.all, and never use map as a filter.

Guides
Preparing for interviews?

Built in public

The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.

Star on GitHub