CodeZettaInterview Hub

JavaScript · Functional Programming · Junior · Comparison

Explain `map`, `filter`, and `reduce` and when a simple `for` loop is better.

Short Interview Answer

`map` transforms, `filter` selects, `reduce` aggregates; use loops when you need early exit, complex multi-accumulators, or hot-path performance.

Detailed Explanation

`array.map(fn)` returns a new array of mapped values; `filter(predicate)` keeps matching elements; `reduce(fn, init)` folds to a single value. Chaining them is expressive but can create intermediate arrays — sometimes `reduce` once or a `for` loop is clearer/faster. Prefer declarative methods for readability in business logic; prefer loops when profiling shows overhead, when breaking early, or when transforming large typed data. Avoid reduce abuse for simple maps/filters.

Example

const nums = [1, 2, 3, 4];
const sumSquares = nums
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .reduce((a, n) => a + n, 0);

Interview Tip

Mention intermediate allocations — mid-level performance awareness.

Common Mistake

Using `reduce` for everything as a flex, harming readability.

Did you know this answer?