admin管理员组

文章数量:1429844

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.

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.

Share Improve this question asked Dec 8, 2020 at 8:53 Chrissi GrilusChrissi Grilus 1,4153 gold badges14 silver badges23 bronze badges 5
  • 5 Depends - do you want to avoid mutating the array? Note that a mutation is not bad by itself, depends on your use case. – VLAZ Commented Dec 8, 2020 at 8:54
  • I'm exaggerating, but it's like asking "is it OK to add two numbers or should I multiply them?". It really depends on how you want/need from the result. – Felix Kling Commented Dec 8, 2020 at 8:55
  • I don't understand the question, are you unsure about what does mutate means? (the title implies you seems unsure about that, but the body is a bit different) – Pac0 Commented Dec 8, 2020 at 8:55
  • "Should I use let". Are you under the impression that you are not allowed push to arrays defined with const? You are NOT allowed to reassign the variables with const like array = [1,2]. You are allowed to mutate the arrays and objects by changing their properties. Like const a = {} and a.key1 = 'value' is allowed. But, a = { key2: 'value 2 '} is not allowed – adiga Commented Dec 8, 2020 at 9:23
  • Its exactly that usecase. An array to wich I push an object. I can see now that mutating the array is usually not a problem and can be done with const. – Chrissi Grilus Commented Dec 8, 2020 at 10:58
Add a ment  | 

1 Answer 1

Reset to default 6

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;
}

本文标签: javascriptIs Arraypush() mutating the arrayStack Overflow