How to Effectively Use Deep Copy and Shallow Copy in JavaScript

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 4 min read
How to Effectively Use Deep Copy and Shallow Copy in JavaScript Banner Image
How to Effectively Use Deep Copy and Shallow Copy in JavaScript Banner Image

When working with JavaScript, you'll often encounter the need to copy objects or arrays. However, not all copying methods are created equal. Understanding the difference between deep copy and shallow copy is crucial for avoiding unintended side effects in your code. This comprehensive guide will delve into the mechanics of deep copy and shallow copy, their differences, how to implement them, and real-life scenarios where each type is useful.

1. What is a Shallow Copy?

A shallow copy of an object is a copy where only the top-level properties are duplicated. The references to nested objects or arrays are copied, but the objects themselves are not duplicated. This means that if the nested objects or arrays are modified, those changes will be reflected in both the original and the copied object.

Example of Shallow Copy:

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

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

// Modifying the nested object in the shallow copy
shallowCopy.address.city = 'Los Angeles';

console.log(original.address.city); // Output: Los Angeles
console.log(shallowCopy.address.city); // Output: Los Angeles

Explanation: In the example above, when we change the city in shallowCopy, the change also appears in the original object. This is because the address object is only a reference in the shallow copy, not a duplicate.

2. What is a Deep Copy?

A deep copy duplicates every level of an object or array, not just the top level. This means that nested objects or arrays are also copied, and any changes made to the deep copy do not affect the original object.

Example of Deep Copy:

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

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

// Modifying the nested object in the deep copy
deepCopy.address.city = 'Los Angeles';

console.log(original.address.city); // Output: New York
console.log(deepCopy.address.city); // Output: Los Angeles

Explanation: In this example, changing the city in deepCopy does not affect the original object. This is because the address object is fully duplicated in the deep copy.

3. How to Perform a Shallow Copy in JavaScript

There are several ways to perform a shallow copy in JavaScript:

  • Using Object.assign(): This method is commonly used for creating shallow copies of objects.
  • Using the Spread Operator (...): The spread operator is a concise way to perform a shallow copy of arrays or objects.

Example:

// Shallow copy using Object.assign
const copy1 = Object.assign({}, originalObject);

// Shallow copy using the spread operator
const copy2 = { ...originalObject };

4. How to Perform a Deep Copy in JavaScript

Deep copying can be a bit trickier. Here are a few methods:

  • Using JSON Methods: JSON.stringify() and JSON.parse() are commonly used for deep copying simple objects. However, this method does not work with functions, undefined, or special types like Date or Map.
  • Using Lodash's cloneDeep Method: Lodash, a popular JavaScript utility library, provides a reliable cloneDeep method for deep copying objects and arrays.

Example:

// Deep copy using JSON methods
const deepCopy1 = JSON.parse(JSON.stringify(originalObject));

// Deep copy using Lodash
const deepCopy2 = _.cloneDeep(originalObject);

5. Pros and Cons of Shallow Copy and Deep Copy

Shallow Copy

Pros:

  • Faster and less memory-intensive.
  • Sufficient for simple objects without nested structures.

Cons:

  • Not suitable for complex objects with nested structures.
  • Changes to nested objects affect both the copy and the original.

Deep Copy

Pros:

  • Completely independent copy of the original object.
  • Safe for complex objects with nested structures.

Cons:

  • Slower and more memory-intensive.
  • Requires more complex logic or third-party libraries.

6. Real-Life Use Cases

Shallow Copy Use Case:

When working with configurations or settings that may have default values, a shallow copy is often sufficient. For instance, if you need to copy an object with user settings, and you only plan to override some of the top-level properties, a shallow copy would be appropriate.

Deep Copy Use Case:

A deep copy is essential when dealing with large datasets or state management in frameworks like React. For example, in a Redux store, you might want to deep copy the state to prevent unintended mutations that could lead to bugs.

Conclusion

Understanding the difference between deep copy and shallow copy in JavaScript is vital for effective coding, especially when dealing with complex data structures. By using the appropriate method based on the complexity and requirements of your project, you can avoid common pitfalls and ensure that your code behaves as expected. Whether you’re working with simple objects or intricate nested structures, knowing when to use a shallow copy or a deep copy will make your JavaScript applications more robust and maintainable.

Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.

Copyright © 2024 Mbloging. All rights reserved.