Shallow Copy Vs Deep Copy

Shallow Copy Vs Deep Copy

Table of contents

Hello Fellow Readers, Hope you all are doing good. Many a times, we are asked this question in the interviews, specially the output based questions. Lets try to understand these terms.

Shallow Copy

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object. Thats why, when you change the values in source object or copied object, values in both the objects change.

  • Referencing the object with new variable
const srcObj = {
name: "Roma",
hobby: "Reading"
};

const copiedObj = srcObj;

copiedObj.hobby = "Singing";

console.log(srcObj );
console.log(copiedObj);

Output

image.png

  • Spread Operator
const srcObj = {
name: "Roma",
hobby: "Reading"
};

const copiedObj = {...srcObj};

copiedObj.hobby = "Singing";

console.log(srcObj );
console.log(copiedObj);

Output

image.png

It may look like it provides deep copy but it doesn’t provide a complete deep copy. It only provides deep copy if the objcts are not nested. To understand this better, lets look an example.

const srcObj = {
name: "Roma",
hobby: "Reading",
citizen: {
            country: "India",
            city: "Mumbai"
}
};

const copiedObj = {...srcObj};

copiedObj.citizen.city= "Bangalore";

console.log(srcObj );
console.log(copiedObj);

Output

image.png

As citizen is the nested object, its the shallow copy. So, the value of city is changed for both the objects.

  • Using Object.assign()

    It works very similar to spread operator lets see the example below.

      const srcObj = {
      name: "Roma",
      hobby: "Reading",
      citizen: {
                  country: "India",
                  city: "Mumbai"
      }
      };
    
      const copiedObj = Object.assign({}, srcObj);
    
      copiedObj.citizen.city= "Bangalore";
    
      console.log(srcObj );
      console.log(copiedObj);
    

    Here is the output, where the value for city us changed for both the objects.

Deep Copy

A deep copy of an object is a copy whose properties do not share the same references as those of the source object. Thats why when you change the value of property of any one object, the other object wont be affected.

  • JSON Parse and Stringify method

The best way to do complete deep copy is by using JSON methods. Lets see the example.

const srcObj = {
name: "Roma",
hobby: "Reading",
citizen: {
            country: "India",
            city: "Mumbai"
}
};

const copiedObj = JSON.parse(JSON.stringify(srcObj));

copiedObj.citizen.city= "Bangalore";

console.log(srcObj );
console.log(copiedObj);

Output

image.png

  • The other approach is writing the custom function to deep copy the object, it is also very commonly asked in interviews.

       function deepCopy (obj) {
        if (obj === null || typeof obj !== "object") {
          return obj;
        }
    
        if (obj instanceof Date) {
          return new Date(obj.getTime());
        }
    
        if (Array.isArray(obj)) {
          return obj.map(item => deepCopy(item));
        }
    
        const copy = {};
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            copy[key] = deepCopy(obj[key]); 
          }
        }
    
        return copy;
      };
    
      const srcObj = {
      name: "Roma",
      hobby: "Reading",
      citizen: {
                  country: "India",
                  city: "Mumbai"
      }
      };
    
      const copiedObj = deepCopy(srcObj);
    
      copiedObj.citizen.city= "Bangalore";
    
      console.log(srcObj );
      console.log(copiedObj);
    

Output

That's it!! 😍 Hope this article was useful and you got the basic understanding regarding shallow and deep copy.

*References: *

developer.mozilla.org/en-US/docs/Glossary/D..