Answer the question
In order to leave comments, you need to log in
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);
const egg = { name: "Humpty Dumpty" };
egg.isBroken = false;
console.log(egg);
const egg = { name: "Humpty Dumpty" };
const newEgg = egg;
newEgg.name = "Errr ... Not Humpty Dumpty";
const obj1 = {
val: true
}
const obj2 = {
string: "string"
}
obj1 = obj2
const obj = this.props.item
obj.id = "newId1"
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question