What is a deep copy in JavaScript with example

  • javascript
  • 54 Views
  • 4 Min Read
  • 9 Jul 2024

Hey, fellow developers! Have you wondered about JavaScript deep copying? It's the process of creating exact duplicates of objects, even those nested within each other, to safeguard your data and prevent unexpected changes.

 

In this article, we will learn about deep copying, which is important in web development. You will learn different ways to use it in your projects and how it works.

 

Are you excited to learn? Let's get started!

 

Table of contents

 

  1. What is a deep copy?
  2. Why should we use deep copy?
  3. How many ways can we create a deep copy?
  4. Which is the best method for implementing deep copying?
  5. When should we use the deep copy?

 

 

1. What is a deep copy?

 

Deep copying is like making a photocopy of something. It creates an exact duplicate of an object or list in JavaScript, including everything inside it. This way, nothing gets left out, and your data stays safe and sound in your web apps.

 

 

2. Why should we use deep copy?

 

Deep copying is important because it creates a separate copy of an object, including all nested objects, ensuring that modifications made to the copy do not affect the original.

 

If you don't use deep copying and change nested objects in a copied object, it can mess up the original object, causing unexpected issues. 

 

Here's a quick example:

 
// Original object with nested structure
const originalObject = {
    name: 'Elena',
    age: 21,
    city: "USA",
    preferences: {
        theme: 'dark',
        language: 'English'
    }
};

// Copying without deep copy
const clonedObject = originalObject;

// Modify object property and nested property in copied object
clonedObject.preferences.theme = 'light';
clonedObject.name = 'John';

console.log(originalObject);
console.log(clonedObject);
 
Output:
 
// { name: 'John', age: 21, city: 'USA', preferences: {theme: 'light', language: 'English'} }

// { name: 'John', age: 21, city: 'USA', preferences: {theme: 'light', language: 'English'} }

 

In this example, modifying the preferences.theme and name property in the clonedobject, also impacts the original object, possibly creating unexpected outcomes, which is why it's important to use deep copying to avoid such difficulties.

 
Here's an example using deep copy:
 
// Deep copy using JSON serialization
const deepClone = JSON.parse(JSON.stringify(originalObject));

// Modify nested property in deep copy
deepClone.preferences.theme = 'light';
deepClone.name = 'John';

console.log(originalObject);
console.log(deepClone);
 
Output:
 
// {name: 'Elena', age: 21, city: 'USA', preferences: { theme: 'dark, language: 'English' } }

// {name: 'John', age: 21, city: 'USA', preferences: {theme: 'light, language: 'English' } }
 
By using deep copy in the above example, modifying the preferences.theme property in the deepClone does not affect the originalObject, demonstrating the necessity and benefits of deep copying.
 
 

3. How many ways can we create a deep copy?

 

In JavaScript, you have different ways to make deep copies. Let's look at three popular methods, each with its own advantages and things to keep in mind. And don't worry, I'll show you code examples to make it easy to understand.

 

  • Using JSON methods:
  • Using libraries like Lodash:
  • Using a custom recursive function:

 

#1. Using the JSON method

 

Deep copying can be achieved by serializing the original object to a JSON string using JSON.stringify(), and then deserializing it back into a new object using JSON.parse().

 
// Original object with nested structure
const originalObject = {
    name: 'Elena',
    age: 21,
    city: "USA",
    preferences: {
        theme: 'dark',
        language: 'English'
    }
};

// Deep copy using JSON serialization
const deepClone = JSON.parse(JSON.stringify(originalObject));

// Modify nested property in deep copy
deepClone.name = 'John';
deepClone.preferences.language = "Hindi"

console.log(originalObject);
console.log(deepClone);

 

Output:

 

// {name: 'Elena', age: 21, city: 'USA', preferences: { theme: 'dark, language: 'English' } }

// {name: 'John', age: 21, city: 'USA', preferences: { theme: 'dark, language: 'Hindi' } }

 

 

#2. Using libraries like Lodash:

 

Libraries like Lodash provide utility functions such as _.cloneDeep() specifically designed for deep copying objects.

 
const _ = require('lodash');

const originalObject = {
    name: 'Elena',
    age: 21,
    preferences: {
        theme: 'dark',
        language: 'English'
    }
};

const deepClone = _.cloneDeep(originalObject);

// Modify nested property in deep copy
deepClone.name = "John"
deepClone.preferences.language = 'Hindi';

console.log(originalObject);
console.log(deepClone);
 
Output:
 
// {name: 'Elena', age: 21, preferences: { theme: 'dark, language: 'English' } }

// {name: 'John', age: 21, preferences: { theme: 'dark, language: 'Hindi' } }
 
 

#3. Custom Recursive Function:

 

You can create a custom recursive function to manually copy each property and nested object, ensuring a complete duplicate of the original object.

 
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj; // Return the original value if it's not an object
    }

    // Create a new object or array to hold the copied properties
    const clone = Array.isArray(obj) ? [] : {};

    // Iterate over each property in the object
    for (let key in obj) {
        // Recursively copy nested objects and arrays
        clone[key] = deepClone(obj[key]);
    }

    return clone; // Return the copied object
}

// Example usage:
const originalObject = {
    name: 'Elena',
    age: 21,
    preferences: {
        theme: 'dark',
        language: 'English'
    }
};

const clonedObject = deepClone(originalObject);
clonedObject.name = "John"
clonedObject.preferences.language = "Hindi"

console.log(clonedObject);
console.log(originalObject);
 
Output:
 
// {name: 'John', age: 21, preferences: { theme: 'dark, language: 'Hindi' } }

// {name: 'Elena', age: 21, preferences: { theme: 'dark, language: 'English' } }

 

You can achieve similar results using Object.assign() and the spread operator (...).

 
Important: The Object.assign() and the spread operator (...) produce shallow copies. When handling nested objects or arrays, they only duplicate the immediate properties, not the nested structures. That is the main difference between shallow copy and deep copy
 
 

4. Which is the best method for implementing deep copying?

 

The best method for deep copying in JavaScript is typically using JSON for its simplicity and reliability. It's best suited for simple data structures when performance is not critical.

 

However, for more complex scenarios or better performance, consider custom recursive functions or libraries like Lodash. However, you can choose the method based on your project's specific needs.

 

 

5. When should we use the deep copy?

 

Sometimes you need an exact copy of something in JavaScript, including everything inside it. That's where deep copying comes in handy. It helps you make sure nothing unexpected happens to the original data. This way, your data stays safe and sound even after you make changes to the copy.

 

Deep copy is highly used whenever we work with complex data structures like software development, data processing, and AI/ML or game development. It's all about making sure you have separate copies of your stuff, so nothing goes wrong unexpectedly.

 

 

Conclusion

 

Understanding deep copying in JavaScript is important to preserve data integrity and prevent unintended changes to objects, especially when working with nested structures. It is important to use deep copy whenever you need separate duplicates of an object, including all nested properties, to maintain data integrity. Now is the time to practice, so practice and use this deep copy well.

 

If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get the answer soon.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....