How Spread Operator is Scamming you

masteing_the_code

Joel Jose

Posted on May 29, 2024

How Spread Operator is Scamming you

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);
Enter fullscreen mode Exit fullscreen mode

Output :

{ name: 'John' }
{ name: 'Doe' }
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output :

{ name: 'John', dob: { year: 2024 } }
{ name: 'Doe', dob: { year: 2024 } }
Enter fullscreen mode Exit fullscreen mode

Spread operator shallow copy

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!💪

💖 💪 🙅 🚩
masteing_the_code
Joel Jose

Posted on May 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How Spread Operator is Scamming you
typescript How Spread Operator is Scamming you

May 29, 2024