Q12 of 40 · JavaScript

What is the difference between `map()`, `filter()`, `reduce()`, and `forEach()`?

JavaScriptJuniorjavascriptarraysfunctionalmapfilterreduceforEach

Short answer

Short answer: `map()` transforms each element into a new same-length array. `filter()` returns a new array with only matching elements. `reduce()` accumulates elements into a single value. `forEach()` iterates for side effects only, returning `undefined`. The first three are immutable and chainable.

Detail

These four methods are the foundation of functional-style array processing in JavaScript.

map(): Applies a callback to each element and returns a new array of the same length. The original array is unchanged. Use when transforming data.

filter(): Tests each element with a predicate and returns a new array of only passing elements. The result may be shorter than the input. Use when selecting a subset.

reduce(): Applies a callback with an accumulator against each element left-to-right, producing a single output value. The most flexible but most complex. Use for sums, grouping, or building objects from arrays.

forEach(): Iterates and calls the callback for each element purely for side effects. Always returns undefined. Not chainable. Use when you do not need a new array.

In test automation: These methods are used constantly when processing API response arrays, filtering test data, mapping element handles to text content, and building assertion datasets.

// EXAMPLE

const users = [
  { name: "Alice", score: 80 },
  { name: "Bob",   score: 45 },
  { name: "Carol", score: 92 },
];

// map — extract names
const names = users.map(u => u.name);
// ["Alice", "Bob", "Carol"]

// filter — pass threshold
const passing = users.filter(u => u.score >= 50);
// [{Alice,80}, {Carol,92}]

// reduce — total score
const total = users.reduce((sum, u) => sum + u.score, 0); // 217

// chain: names of passing users
const passingNames = users.filter(u => u.score >= 50).map(u => u.name);
// ["Alice", "Carol"]

// forEach — side effect only
users.forEach(u => console.log(u.name));

// WHAT INTERVIEWERS LOOK FOR

Understanding that map/filter/reduce return new arrays (immutability) while forEach does not. Chaining ability. Bonus: knowing map always produces same-length output while filter may not.

// COMMON PITFALL

Using forEach when you need a transformed array — you end up pushing to an external array as a side effect instead of using map. Also: omitting the initial value in reduce causes bugs on empty arrays.