8

I constantly have problem with keeping this in my head, and I can't google it out quickly. That's why I'm putting this question here.

Every time I'm calling a method like concat, sort or slice, I'm asking myself: does it create and return a new array, or it just modifies and returns array it was applied to?

Q: could you please list methods that change the original array vs methods that construct and return a new array?

Methods like pop or push are not in the game, it's obvious what they do.

Dan
  • 55,715
  • 40
  • 116
  • 154
  • 3
    MDN lists `Array` methods grouped under [Mutator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods), [Accessor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Accessor_methods), and [Iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods). – Jonathan Lonowski Dec 13 '13 at 16:28
  • 1
    Also, this is a likely duplicate of [Which JavaScript Array functions are mutating?](http://stackoverflow.com/q/9009879). – Jonathan Lonowski Dec 13 '13 at 16:42
  • Does this answer your question? [Which JavaScript Array functions are mutating?](https://stackoverflow.com/questions/9009879/which-javascript-array-functions-are-mutating) – Krzysztof Kaczyński Apr 18 '22 at 23:37

1 Answers1

15

The full list of methods on array instances that change the values or number of values in the array is this one:

  • Array.prototype.push
  • Array.prototype.pop
  • Array.prototype.shift
  • Array.prototype.unshift
  • Array.prototype.splice
  • Array.prototype.reverse
  • Array.prototype.sort
  • Array.prototype.fill
  • Array.prototype.copyWithin

Aditionally, changing the length property can remove elements from the array (if you decrease it) or add undefined items to the array (if you increase it).

Finally, changing the properties of the arrays with keys that are positive integer-like strings like '0','1', '3000', etc will change the values at those indexes and possibly increase the length of the array.

Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
Tibos
  • 27,507
  • 4
  • 50
  • 64