Skip to the page

Arrays, collections and copying · core

Array methods: mutating vs copying

Know which array methods change the array in place (push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin) and which return a new array (map, filter, slice, concat, flat, toSorted, toReversed, toSpliced, with), because React and Redux state depends on not mutating.

The notes

What you must know

  • map returns a new array of the same length. forEach returns undefined, can't break, and ignores the promises async callbacks return (they all run at once and nobody waits).
  • ES2023 copying versions of mutating methods: toSorted, toReversed, toSpliced and with(index, value).
  • sort() without a comparator converts values to strings, so [1, 10, 2] stays [1, 10, 2]. Numeric: (a, b) => a - b. The comparator must return a number, not a boolean. sort is stable since ES2019.
  • find/findIndex/findLast/findLastIndex; some and every stop early; includes uses SameValueZero (finds NaN), indexOf uses === (doesn't).
  • reduce passes (acc, cur, index, array). Without an initial value it starts from the first element; on an empty array without an initial value it throws TypeError.
  • Holes: forEach, map and filter skip holes in sparse arrays. Array(3) has three holes; Array.from({ length: 3 }, fn) creates real values.
  • at(-1) reads the last element. flat(depth) and flatMap flatten. Object.groupBy returns a null-prototype object; Map.groupBy returns a Map (ES2024).

The red pen

Common traps: mistake → fix

  • Mistake: sort sorts numbers numerically

    Fix: by default it compares strings.

  • Mistake: forEach waits for async callbacks

    Fix: it doesn't; use for...of with await or Promise.all.

  • Mistake: ['1','7','11'].map(parseInt) gives [1, 7, 11]

    Fix: the index is passed as the radix.

  • Mistake: A comparator can return true or false

    Fix: it must return negative, zero or positive.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between map and forEach?
  2. Which array methods mutate? Why does it matter for React state and Redux?
  3. Why does [1, 10, 2].sort() give [1, 10, 2]? Sort objects by two keys.
  4. What are toSorted, toSpliced, with and Object.groupBy?
  5. What happens when you use an async callback in forEach, and how do you fix it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview