Hi guys, all of us are familiar with the spread operator that is denoted by '…
', and it is most commonly used for copying array or objects. But did you know that it is scamming us in the name of copy.
Let me make things clear...
Try to guess the output of this code :
const obj = {
name: 'John',
};
const copyObj = { ...obj };
copyObj.name = 'Doe';
console.log(obj);
console.log(copyObj);
Output :
{ name: 'John' }
{ name: 'Doe' }
Great⭐! Now how about this one :
const obj = {
name: 'John',
dob: {
year: 2000
}
};
const copyObj = { ...obj };
copyObj.name = 'Doe';
copyObj.dob.year = 2024
console.log(obj)
console.log(copyObj)
Output :
{ name: 'John', dob: { year: 2024 } }
{ name: 'Doe', dob: { year: 2024 } }
Wait…. now what happened here? Why did the first object also have its value changed?
Explaining the scam
The reason for this is the shallow copy
that spread operator performs while copying an object.
When we refer to shallow copy
, it means that the values of the first level properties are copied perfectly and modifying them does not affect the original object. Meanwhile the spread operator only copies the references of other properties and modifying them, changes the original object.
Over to you
This is just one of the property of spread operator, there is more to learn about it and ways to avoid shallow copy when not required. So go out there and find your answers.
So, that's all, guys!😉
Just keep learning!💪
Top comments (0)