10

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

1 Answer 1

17

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.

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

Comments

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.