Javascript: Why don't array methods return a new array?

63 views Asked by At

I understand that the reason methods on strings return a new string is that strings are immutable, so the method can't modify the string you pass to it.

With an array, if you pass it to a method, that method can modify the array because arrays are mutable. I'm wondering why array methods (and methods on other mutable types) aren't written to return a new array, such that they would be consistent with the methods on primitive types like strings.

For example, arr.map() might be written like this:

function map = (arr) => {
  ...<logic>...
}

where it could be written like this:

function map = (arr) => {
  let arr_ = arr.slice()
  ...<logic>...
  return arr_
}

Is there a reason methods on mutable types aren't written in this way?

0

There are 0 answers