Open In App

What is Deep Copy In JavaScript ?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a deep copy refers to creating a completely independent duplicate of a complex data structure, such as an object or an array, including all nested objects and arrays within it. Unlike a shallow copy, a deep copy ensures that changes made to the original data structure do not affect the copied one, and vice versa.

To achieve a deep copy, each level of the data structure must be recursively traversed, and new objects or arrays must be created to hold the copied values. This process ensures that every nested object or array is duplicated, rather than just copying references to them.

Example: Here, JSON.stringify() converts the original object to a JSON string, and JSON.parse() then parses that string back into a new object. This process creates a deep copy of the original object, including its nested properties. As a result, modifying the properties of the original object after copying does not affect the deep copy.

Javascript




const originalObject = {
    name: 'John',
    age: 30,
    address: {
        city: 'New York',
        country: 'USA'
    }
};
 
// Deep copy using JSON methods
const deepCopyObject =
    JSON.parse(JSON.stringify(originalObject));
 
// Modifying the originalObject
originalObject.name = 'Alice';
originalObject.address.city = 'Los Angeles';
 
console.log(originalObject);
console.log(deepCopyObject);


Output

{
  name: 'Alice',
  age: 30,
  address: { city: 'Los Angeles', country: 'USA' }
}
{
  name: 'John',
  age: 30,
  address: { city: 'New York', country: 'USA' }
}

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads