66

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?

1

3 Answers 3

97

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

Sign up to request clarification or add additional context in comments.

3 Comments

Mutator link is currently incorrect, it is now: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@zamnuts Thanks. And, looks like all the links needed some updating.
looks like the mutator method list was removed from MDN docs. see this SO answer instead: stackoverflow.com/a/54836218/1481489
11

I found this website called Doesitmutate

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

Comments

10

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(...)

4 Comments

With ES2015 it's just: const sortArray = [ ...dontMutateMe ].sort(...);
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.
Correct me if I'm wrong @jasonleonhard, but woudln't const sortArray = dontMutateMe.concat() create a new array just as const sortArray = [ ...dontMutateMe ] would?
Yes, thats what @jasonleonhard said, concat and spread both clone your array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.