61

I am writing an Array-derived class in JavaScript and need to know which functions to overload so that I can be aware of changes made to the array.

I know Array.push() and Array.splice() are mutating. Is there a definitive list of any others?

devios1
  • 36,899
  • 45
  • 162
  • 260
  • Does this answer your question? [How to remember if a method mutates the original array?](https://stackoverflow.com/questions/54836118/how-to-remember-if-a-method-mutates-the-original-array) – Eyeslandic Jul 18 '22 at 13:01

3 Answers3

89

You can find the list on MDN as Mutator methods (along with Accessor and Iteration methods):

Jacob
  • 2,212
  • 1
  • 12
  • 18
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 1
    Mutator link is currently incorrect, it is now: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Mutator_methods – zamnuts Oct 13 '13 at 06:52
  • @zamnuts Thanks. And, looks like all the links needed some updating. – Jonathan Lonowski Oct 13 '13 at 06:56
  • 1
    looks like the mutator method list was removed from MDN docs. see this SO answer instead: https://stackoverflow.com/a/54836218/1481489 – zamnuts Oct 17 '20 at 22:43
10

I found this website called Doesitmutate

Have the list of all functions - and tells whether it mutates or not.

Sooraj
  • 9,717
  • 9
  • 64
  • 99
9

You can also use .concat(), before using your mutation method, to ensure you are not mutating your arrays, eg

const dontMutateMe = [4,5,1,2,3];
const sortArray = dontMutateMe.concat().sort(...)
Vinnie James
  • 5,763
  • 6
  • 43
  • 52
  • 8
    With ES2015 it's just: `const sortArray = [ ...dontMutateMe ].sort(...);` – Freewalker Jun 16 '17 at 04:29
  • As nice as ES6 is, ES6 is not always available, luckily concat is. Good to know concat works well in those cases. Just remember, it is not always best to create a whole new array to do basic operations, there is a cost to copying. – jasonleonhard Feb 14 '22 at 20:19