0

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.

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. 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. 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) 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 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. Commented Dec 8, 2020 at 10:58

1 Answer 1

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