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.
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.
-
3
MDN lists
Array
methods grouped under Mutator, Accessor, and Iteration. – Jonathan Lonowski Commented Dec 13, 2013 at 16:28 - 1 Also, this is a likely duplicate of Which JavaScript Array functions are mutating?. – Jonathan Lonowski Commented Dec 13, 2013 at 16:42
- Does this answer your question? Which JavaScript Array functions are mutating? – Krzysztof Kaczyński Commented Apr 18, 2022 at 23:37
1 Answer
Reset to default 17The 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.