CodePark/ questions / Arrays & objects
START PRACTICINGPRACTICE
Frontend question · JavaScript › Arrays & objects

Which array methods mutate the array and which return a new one? Why does it matter?

Some array methods change the array in place, and others return a new array or value. It matters whenever other code shares the same array.

Mutating methods (change the array in place):
push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin.

Be careful with sort and reverse. They also return the same array, so they look like they make a new one, but they do not.

Non-mutating methods (return a new array or value):
map, filter, slice, concat, flat, flatMap and reduce.

ES2023 added copying versions of the mutating ones: toSorted, toReversed, toSpliced and with(index, value).

Why it matters:

  • React and Redux detect state changes by reference. If you change an array in place, the reference stays the same, so the UI may not update.
  • Bugs happen when a function sorts an array it received as an argument. The caller's array changes too.

The safe pattern is [...arr].sort() or arr.toSorted().

  • Mutating methods are push, pop, shift, unshift, splice, sort, reverse and fill.
  • Non-mutating methods include map, filter, slice, concat and reduce.
  • ES2023 added toSorted, toReversed, toSpliced and with, which return copies.
  • React detects changes by reference, so it needs new arrays.