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.
What is the difference between map, filter, and reduce? When is forEach the wrong choice?
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'.
flatMap versus reduce to flatten?
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.
Why is mutating inside map a bug?
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.
Sum with reduce — missing initial value?
Pass 0. Empty array throws without an initializer. nums.reduce((a,n)=>a+n, 0). Reducing to an object I pass {}.
When is a for loop clearer than reduce?
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