Understanding the Difference Between Shallow Copy and Deep Copy in JavaScript – Interview Question

Posted by

JavaScript Interview Question – Shallow Copy vs Deep Copy

JavaScript Interview Question – Shallow Copy vs Deep Copy

When working with JavaScript, it’s important to understand the difference between shallow copy and deep copy, especially when dealing with complex data structures. These concepts often come up in JavaScript interviews, so it’s important to be prepared.

Shallow Copy

A shallow copy of an object means creating a new object and then copying the values of the original object into the new object. However, if the original object contains nested objects, those nested objects are not duplicated – they are simply referenced in the new object.

Deep Copy

A deep copy, on the other hand, means creating a new object and then recursively copying the values of the original object into the new object. This includes any nested objects, so the new object is entirely separate from the original object.

Example

Let’s take a look at an example to illustrate the difference between shallow copy and deep copy:

      
        const original = {
          name: 'John',
          age: 30,
          address: {
            city: 'New York',
            country: 'USA'
          }
        };

        // Shallow copy
        const shallowCopy = Object.assign({}, original);

        // Deep copy
        const deepCopy = JSON.parse(JSON.stringify(original));
      
    

In the above example, the shallow copy of the original object will create a new object with the same top-level properties, but the ‘address’ property will still reference the same object as the original. On the other hand, the deep copy will create an entirely new object with its own ‘address’ property that is separate from the original object.

Conclusion

Understanding the difference between shallow copy and deep copy is important in JavaScript, especially when working with complex data structures. In interviews, it’s important to be able to explain these concepts and also demonstrate how to create shallow and deep copies in JavaScript.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jayapalagowda
10 months ago

Very good explanation

@prasantakumarroutray2105
10 months ago

As usual….your explanation is awesome..keep it up and one more thing java script full debuging and total end to end tutorial please make 😀😀😀😀😀😀