I understand spread operators make Shallow copy of objects i.e the cloned object refers to the same reference as the original object. But the actual behaviour seems contradicting and confusing.
const oldObj = {a: {b: 10}};
const newObj = {...oldObj};
oldObj.a.b = 2;
newObj //{a: {b: 2}}
oldObj //{a: {b: 2}}
Above behaviour makes sense, newObj is also updated by updating oldObj because they refer the same location.
const oldWeirdObj = {a:5,b:3};
const newWeirdObj = {...oldWeirdObj};
oldWeirdObj.a=2;
oldWeirdObj //{a:2,b:3}
newWeirdObj //{a:5,b:3}
I'm not understanding, why newWeirdObj is not updating similar to oldWeirdObj? They are still referring to the same location if i am not wrong, but why is update to oldWeirdObj not updating newWeirdObj ?
See Question&Answers more detail:os