DEV Community

Claudio Guedes
Claudio Guedes

Posted on • Edited on

Shallow vs Deep Copy of Objects in JavaScript

When we need to copy an object to another object, we generally use something like this:

const mainObject = { id: 1 };
const secondaryObject = { ...mainObject };
Enter fullscreen mode Exit fullscreen mode

But this only works for copying the shallow properties of the object. If we have a case like the following code, the scenario changes:

const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const secondaryObject = { ...mainObject };
Enter fullscreen mode Exit fullscreen mode

The property user won't be copied; it will still be related to mainObject. So, if we alter the user property, it will also affect mainObject. To solve this, we can do the following:

const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const deepCopy = JSON.parse(JSON.stringify(mainObject));
Enter fullscreen mode Exit fullscreen mode

Now, we have a deep copy of mainObject, with two distinct memory addresses.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay