Chrissi Grilus
Chrissi Grilus

Reputation: 1375

Is Array.push() mutating the array?

I am doing:

  const array = []

  ...
  array.push({x, y})

Is that considered a bad practise. Should I use let or spread the array because "push" is considered a mutating action. It is working though.

Upvotes: 0

Views: 3918

Answers (1)

Quentin
Quentin

Reputation: 943579

Is Array.push() mutating the array?

Yes

Is that considered a bad practise. Should I use let or spread the array because "push" is considered a mutating action.

Generally not.

There are times when treating data as immutable is useful, or even essential (such as when you are updating a Redux store).

In those cases, push still isn't a bad idea, you just shouldn't do it to your original array.

For example, this is fine and has no side effects:

function functionalFunction(input) {
    const output = [...input];
    output.push({x, y});
    // A bunch of other operations that mutate the array go here
    // Be careful not to mutate any objects in the array
    return output;
}

Upvotes: 6

Related Questions