'javascript: List of array methods that change the array they were applied to
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Krzysztof Kaczyński |