const girl = {
name: 'Anna',
info: { age: 20, number: 123 }
};
const newGirl = { ...girl };
newGirl.info.age = 30;
console.log(girl.info.age, newGirl.info.age);
The output is 30 30, we copy the properties of the girl object into the newGirl object using the spread operator. This operator creates a shallow copy of the object. Shallow copies are not safe from mutations.
Lets see another example
function test(obj) {
const output = { ...obj };
output.age = 30;
return output;
}
let person = { age: 10 }
let newPerson = test(person);
console.log(newPerson.age, person.age); // output is 30 10
As you can see the second example also use a spread operator to create a copy of the object. Why does it do not behave the same as the first example? Why it does not affect original object field data?