DEV Community

Sujal Gupta
Sujal Gupta

Posted on • Edited on

How to copy an Object in Javascript?

Any change made in captain object will also reflect in person object.

const person = { name: 'Wes Bos', age: 80 };
console.log(person);
//{name: "Wes Bos", age: 80}
const captain = person;
console.log(captain);
//{name: "Wes Bos", age: 80}
person.age = 90;
console.log(captain);
// {name: "Wes Bos", age: 90} 

Enter fullscreen mode Exit fullscreen mode

See We didn't even made any change to captin but the changes made to person object reflects on captain object as well.
This is because captain is not a copy of person object but it is rather a reference to the person object.
So Any change made in captain object will also reflect in person object.

const cap2 = Object.assign({},person,{age:12,number:99});
console.log(cap2);
const cap3 = {...person};
console.log(cap3);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)