Z
Z
zwezew2019-03-08 22:30:39
JavaScript
zwezew, 2019-03-08 22:30:39

js object mutations - how not to become a sith?

I read about the horrors of mutations in js.
View example

const egg = { name: "Humpty Dumpty" };
egg.isBroken = false;

console.log(egg);

the author calls a mutation. I also read that a mutation is a change in an object by reference (that is, this particular type of change).
To what extent should mutation avoidance be raised to an absolute?
For example, is this example scary, where the object is modified directly?
const egg = { name: "Humpty Dumpty" };
egg.isBroken = false;

console.log(egg);

Or should you avoid only those options where the object does not change directly?
const egg = { name: "Humpty Dumpty" };

const newEgg = egg;
newEgg.name = "Errr ... Not Humpty Dumpty";

Or, for example, this code
const obj1 = {
    val: true
}
const obj2 = {
    string: "string"
}
obj1 = obj2

Or, for example, in react
const obj = this.props.item
obj.id = "newId1"

?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-03-08
@zwezew

They made an elephant out of a fly.
There are specific cases when you cannot mutate, you need to create a new one, for example, if you mutate a state in redux, your components will not see changes, if you detect changes on an object, and hope that by changing part of it, your detector will work, it will also be a bummer . Sometimes it happens that you need the original object, and you took it and mutated it in the process. For example, you need the original array of objects for work, you filter it, rejoice that you have a new array, but forget that the objects in this array are old, and mutate them.
By itself, the mutation is not terrible at all, moreover, it is cheaper to mutate the old object and not create a new one for each sneeze and wait for the old collector to collect it. But as elsewhere in Javascript, you need to think a lot and productively, you must always know what you are mutating and what the consequences will be.
In React, by the way, you can’t almost always mutate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question