DEV Community

Cover image for Deep Copy vs Shallow Copy in JavaScript: Understanding the Differences
Shaikh AJ
Shaikh AJ

Posted on

Deep Copy vs Shallow Copy in JavaScript: Understanding the Differences

Introduction:

When working with objects and arrays in JavaScript, you often come across the concepts of deep copy and shallow copy. These terms refer to different approaches for creating copies of complex data structures. Understanding the differences between deep copy and shallow copy is crucial to avoid unexpected behavior and ensure proper data manipulation. In this article, we will delve into the concepts of deep copy and shallow copy, provide examples to illustrate their usage, and discuss when and why you would choose one over the other.

What is Shallow Copy?

Shallow copying is the process of creating a new object or array and copying the references of the properties or elements from the original data structure. In other words, a shallow copy creates a new data structure that shares the same references as the original. Any modifications made to the copied structure will affect the original, and vice versa.

Example 1:

const originalArray = [1, 2, 3];
const shallowCopy = originalArray;

shallowCopy[0] = 10;

console.log(originalArray); // Output: [10, 2, 3]
console.log(shallowCopy); // Output: [10, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Example 2:

const originalObject = { name: 'John', age: 25 };
const shallowCopy = originalObject;

shallowCopy.age = 30;

console.log(originalObject); // Output: { name: 'John', age: 30 }
console.log(shallowCopy); // Output: { name: 'John', age: 30 }
Enter fullscreen mode Exit fullscreen mode

Explanation:
In both examples, we create shallow copies of the original array and object by assigning them to new variables (shallowCopy). When we modify the first element of the array or the age property of the object, the changes are reflected in both the original and the shallow copy. This is because they share the same references to the underlying data.

When to Use Shallow Copy:

  • When you want to create a new reference to an existing data structure without duplicating its contents.
  • When you need to pass a reference to the original data structure to another part of your code, while keeping it synchronized with any changes.

Why Use Shallow Copy:

  • Shallow copying is more memory-efficient since it avoids duplicating the entire data structure.
  • It allows you to maintain data consistency across different parts of your code that need to access and modify the same data.

What is Deep Copy?

Deep copying, on the other hand, creates a completely independent copy of the original data structure, including all nested objects or arrays. It recursively traverses the entire data structure and creates new instances of all properties or elements.

Example 1:

const originalArray = [1, 2, 3];
const deepCopy = JSON.parse(JSON.stringify(originalArray));

deepCopy[0] = 10;

console.log(originalArray); // Output: [1, 2, 3]
console.log(deepCopy); // Output: [10, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Example 2:

const originalObject = { name: 'John', age: 25 };
const deepCopy = JSON.parse(JSON.stringify(originalObject));

deepCopy.age = 30;

console.log(originalObject); // Output: { name: 'John', age: 25 }
console.log(deepCopy); // Output: { name: 'John', age: 30 }
Enter fullscreen mode Exit fullscreen mode

Explanation:
In both examples, we create deep copies of the original array and object using the JSON.parse(JSON.stringify()) technique. This technique serializes the

original data structure to a JSON string and then parses it back into a new JavaScript object or array, creating a completely independent copy. Modifying the deep copies does not affect the original data.

When to Use Deep Copy:

  • When you want to create an entirely separate copy of a data structure without any shared references.
  • When you need to modify the copied structure independently from the original, without affecting each other.

Why Use Deep Copy:

  • Deep copying ensures data isolation and prevents unintentional modifications to the original data structure.
  • It allows you to work with a copied data structure independently, enabling safe manipulation without impacting the original data.

Other Ways to Create Shallow and Deep Copies

Apart from the examples mentioned above, there are alternative methods to create shallow and deep copies in JavaScript. Let's explore some additional techniques:

Shallow Copy:

  1. Using the spread operator (...):
const originalArray = [1, 2, 3];
const shallowCopy = [...originalArray];
Enter fullscreen mode Exit fullscreen mode
  1. Using the Array.from() method:
const originalArray = [1, 2, 3];
const shallowCopy = Array.from(originalArray);
Enter fullscreen mode Exit fullscreen mode
  1. Using the slice() method:
const originalArray = [1, 2, 3];
const shallowCopy = originalArray.slice();
Enter fullscreen mode Exit fullscreen mode

Deep Copy:

  1. Using libraries like Lodash:
const originalArray = [1, 2, 3];
const deepCopy = _.cloneDeep(originalArray);
Enter fullscreen mode Exit fullscreen mode
  1. Using the structuredClone() method (for browsers that support the structured clone algorithm):
const originalArray = [1, 2, 3];
const deepCopy = window.navigator.vibrate(originalArray);
Enter fullscreen mode Exit fullscreen mode
  1. Custom recursive deep copy implementation:
function deepCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  const copy = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }

  return copy;
}

const originalArray = [1, 2, 3];
const deepCopy = deepCopy(originalArray);
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Understanding the differences between deep copy and shallow copy is essential when working with complex data structures in JavaScript. Shallow copying creates new references to the original data, while deep copying provides independent copies with no shared references. The choice between deep copy and shallow copy depends on your specific requirements and the desired behavior of your code. Consider the trade-offs, performance implications, and the nature of your data when deciding which approach to use. By utilizing the appropriate copy technique, you can ensure proper data manipulation and prevent unexpected side effects in your JavaScript applications.

Top comments (0)