DEV Community

Fatima Alam
Fatima Alam

Posted on • Edited on

JS - Shallow Copy and Deep Copy of an object

Shallow Copy
A shallow copy is a copy of an object whose references are the same as the original object. This means that if you change the value of a property in the shallow copy, it will also change the value of the property in the original object.

const user = {
    name: "Kingsley",
    age: 28,
    job: "Web Developer"
}
const clone = user
Enter fullscreen mode Exit fullscreen mode

Methods -

Spread Operator(…): any object with a nested object will not be deep copied.

const originalObject = { name: "Alice", age: 25 };
const deepCopy =  {...originalObject};

deepCopy.name = "ravi"
console.log("originalObject", originalObject.name) // Alice
Enter fullscreen mode Exit fullscreen mode

Object.assign(): the Object.assign() method should be used to deep copy objects that have no nested objects.

const originalObject = { name: "Alice", age: 25 };
const shallowCopy = Object.assign({}, originalObject);
Enter fullscreen mode Exit fullscreen mode

Deep Copy
A deep copy is a copy of an object whose references are not the same as the original object. This means that if you change the value of a property in the deep copy, it will not change the value of the property in the original object.

Methods -
there different ways to create deep copy of an object.

a)JSON.parse and JSON.stringify: useful for nested object also.

 const originalObject = { name: "Alice", age: 25 };
   const deepCopy = JSON.parse(JSON.stringify(originalObject));
Enter fullscreen mode Exit fullscreen mode

b)structuredClone:

const myDeepCopy = structuredClone(myOriginal);
Enter fullscreen mode Exit fullscreen mode

Recursion:

function deepCopy(obj) {
       if (typeof obj !== 'object' || obj === null) {
           return obj;
       }
       const newObj = Array.isArray(obj) ? [] : {};
       for (let key in obj) {
           if (Object.hasOwnProperty.call(obj, key)) {
               newObj[key] = deepCopy(obj[key]);
           }
       }
       return newObj;
   }
   const originalObject = { name: "Alice", nested: { age: 25 } };
   const deepCopy = deepCopy(originalObject);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)