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' }
}

Previous Article
Next Article

Similar Reads

What is shallow copy and deep copy in JavaScript ?
JavaScript is a high-level, dynamically typed client-side scripting language. JavaScript adds functionality to static HTML pages. Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy.  Shallow CopyWhen a reference variable is copied into a new reference variable using the assignment operator, a
4 min read
How to deep flatten an array in JavaScript?
In this article, we will learn how to deep flatten an array in JavaScript. The flattening of an array is a process of merging a group of nested arrays present inside a given array. Deep flattening means that the array would be completely flattened. Example: Input: [1,2,3,4,5,[6,[7,8,9]]] Output: [1,2,3,4,5,6,7,8,9] This can be done using the follow
2 min read
Deep Dive into Error Handling in JavaScript/Node.js
What is an Error? An error is an illegal operation performed by the user which results in the abnormal working of the program. Types of Errors: Errors can be broadly categorized as Operational Errors: Errors that happen while a program is undertaking a task. For instance, network failure would be an operational errorDeveloper Errors: This type of e
11 min read
Implement Custom Function to Deep clone in JavaScript
In general, cloning means copying one value to another. In JavaScript, there are two types of cloning, i.e. Deep clone and shallow clone. This article is about Deep clones and we will learn about Deep clones. Cloning is a concept that can happen in any data type i.e. it might be a primitive data type (like string, number) or composite data types li
4 min read
How to Deep clone in JavaScript ?
In general, cloning means copying one value to another. In JavaScript, we do cloning i.e. copying one value to another using JavaScript. To be more precise there are two types of cloning in JavaScript. As a programmer, it might be a beginner or veteran he/she should be able to know the differences between Deep clone and shallow clone. As this artic
3 min read
How to deep-freeze an object in JavaScript ?
In this article, we will see what is the problem with objects in JavaScript and why we need to "deep-freeze" an object in JavaScript. We will also learn how to "deep-freeze" an object in JavaScript. Problem with Object in JavaScript: We all know that JavaScript objects are mutable. How can we make them immutable? Define them as const but if we decl
3 min read
How to Deep Clone an Object & Preserve its Type with TypeScript ?
In TypeScript, deep cloning an object by preserving its type consists of retaining the same structure and type information as of original object. Below are the approaches to Deep Clone an Object & Preserve its Type: Table of Content Using JSON.stringify and JSON.parseUsing Object.Assign functionUsing JSON.stringify and JSON.parseIn this approac
2 min read
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore various approaches to deep merging objects in TypeScrip
3 min read
How to do a Deep Comparison Between Two Objects using Lodash?
Deep Comparison between two objects is the process of thoroughly checking their properties and nested objects to determine if they are equal. Below are the possible approaches to do a deep comparison between two objects using Lodash.: Table of Content Using _.isEqual() functionUsing _.isEqualWith() Method with Comparator Function Run the below comm
2 min read
How do we Create a Deep Clone of a Value using Lodash?
Lodash provides the _.cloneDeep() method to create a deep copy of a value, recursively cloning nested objects and arrays. This method ensures that the newly created object has the same value as the original but they are distinct objects in memory. Syntax_.cloneDeep(originalObj)Return Value:This method returns the deep-cloned value. Run the below co
2 min read