JavaScript

map, filter, reduce Interview Questions

map vs filter vs reduce, immutability, and when forEach is the wrong choice.

  • 5Questions with answers
  • 3Difficulty levels

Questions (5)

Browse beginner, intermediate, and advanced questions with answers — hide them when you want to self-test.

Question 1
Interview Beginner
Question

What is the difference between map, filter, and reduce? When is forEach the wrong choice?

Answer:

map returns a new array of the same length, transformed. filter returns a new array of items that pass a test. reduce boils the array down to one value, or rebuilds a more complex structure. forEach is for side effects. It does not return a useful array, and I cannot await in series cleanly without extra work. If I write map and ignore the return value, I should have used forEach. If I am transforming, I use map. I prefer these over a mutating for-loop when the intent is 'make a new list'.

Question 2
Interview Intermediate
Question

flatMap versus reduce to flatten?

Answer:

flatMap maps then flattens one level. reduce can build anything and is easier to get wrong. I pick the smallest named method. I do not mutate the source in map.

Question 3
Interview Beginner
Question

Why is mutating inside map a bug?

Answer:

map's contract is a new array of transformed values. In-place mutate belongs in forEach. I return new objects. I have failed PRs for this.

Question 4
Interview Beginner
Question

Sum with reduce — missing initial value?

Answer:

Pass 0. Empty array throws without an initializer. nums.reduce((a,n)=>a+n, 0). Reducing to an object I pass {}.

Question 5
Interview Intermediate
Question

When is a for loop clearer than reduce?

Answer:

When the accumulator is a page long. I would not golf nested reduce. Interviews may want reduce; I write a readable one. In production I might choose the loop. Judgment.

Practice with AI mock interviews

Run JavaScript mock interviews with AI follow-ups, instant feedback, and analytics on AiLx.

Free to start · No credit card required