Interview Q&A · JavaScript · 12 questions in this topic

Arrays & Array Methods — JavaScript Interview Q&A

All JavaScript topics

The iteration toolkit — map/filter/reduce, mutation vs copy, sorting and flattening. Part of Arrays, Strings & Collections · 204 questions in the JavaScript bank.

How do map, filter and forEach differ?

Answer

map transforms each element, returning a new array (pure pipeline step). filter keeps matching elements in a new array. forEach runs side effects, returning undefined — not chainable, not awaitable per-element.

Transform → map, select → filter, effects → forEach (or for...of).

Example

Example.jsjs
const nums = [1, 2, 3, 4];
nums.filter((n) => n % 2 === 0).map((n) => n * 10); // [20, 40]
// forEach returns undefined — never assign it

How does `reduce` work (and when is it overkill)?

Answer

reduce folds elements into one value via (accumulator, current) plus initial value — sums, groups, lookups, pipelines. Always pass the initial value (empty-array safety, type clarity). Overkill for map/filter-shaped jobs — readability loses to one-liner cleverness.

Initial-value-always is the safety rule.

Example

Example.jsjs
const byDept = users.reduce((m, u) => {
  (m[u.dept] ||= []).push(u);
  return m;
}, {}); // group-by in one pass

Which array methods mutate (and what are the immutable alternatives)?

Answer

Mutating: push/pop/shift/unshift/splice/sort/reverse/fill/copyWithin. Copying: map/filter/slice/concat/toSorted/toSpliced/toReversed/with (ES2023). React/Redux-style state demands copies — mutate a draft or spread new references.

ES2023 non-mutating quartet (toSorted/toSpliced/toReversed/with) ends the copy-then-mutate dance.

Key points

  1. 1Mutate — push/splice/sort/reverse family.
  2. 2Copy — map/filter/slice plus ES2023 toSorted/toSpliced.
  3. 3Rule — framework state wants new references.

Example

Example.jsjs
const sorted = [...a].sort(); // or ES2023: a.toSorted()
const patched = a.with(1, 99);  // copy with index set

💡 New-reference-renders is why immutability matters in UI code.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits