DEV Community

Habib Nuhu
Habib Nuhu

Posted on • Updated on

Understanding Deep vs Shallow Copy in JavaScript: A Comprehensive Guide

When working with JavaScript, understanding the differences between deep and shallow copies is crucial for managing data structures effectively. Whether you're handling arrays, objects, or other data types, knowing how to copy them correctly can prevent unexpected behavior and bugs in your code. In this article, we'll explore what deep and shallow copies are, how they differ, and when to use each type.

What is a Shallow Copy?
A shallow copy of an object is a copy whose properties share the same references as those in the original object. If the object contains nested objects, the references to those nested objects are copied, not the nested objects themselves. This means that changes to the nested objects in the copy will also affect the original object.

Example

const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };

shallowCopy.b.c = 3;

console.log(original.b.c); // Output: 3
Enter fullscreen mode Exit fullscreen mode

In the example above, modifying shallowCopy.b.c also modifies original.b.c because shallowCopy and original share the same reference to the nested object b.

What is a Deep Copy?
A deep copy of an object is a copy that duplicates all levels of the original object's properties. This means that nested objects are also copied, not just their references. Changes to the deep copy do not affect the original object and vice versa.

Example

const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.b.c = 3;

console.log(original.b.c); // Output: 2
Enter fullscreen mode Exit fullscreen mode

In this example, modifying deepCopy.b.c does not affect original.b.c because deepCopy is a completely separate copy of original.

Methods to Create Shallow Copies

1.Object Spread Operator ({...}):

const shallowCopy = { ...original };
Enter fullscreen mode Exit fullscreen mode

2.Array slice Method:

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

3.Object.assign method

const shallowCopy = Object.assign({}, original);
Enter fullscreen mode Exit fullscreen mode

Methods to Create Deep Copies
1.JSON.parse and JSON.stringify:

const deepCopy = JSON.parse(JSON.stringify(original));
Enter fullscreen mode Exit fullscreen mode

Note: This method has limitations, such as not handling functions or undefined properties.

2.Recursive function

function deepCopy(obj) {
  if (obj === null || typeof obj !== 'object') return obj;

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

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

  return copy;
}
Enter fullscreen mode Exit fullscreen mode

When to Use Deep vs Shallow Copy

Shallow Copy:
Use when you need a copy of an object where changes to nested objects should reflect in both the original and the copy.
Suitable for simple objects without nested structures.

Deep Copy:
Use when you need a completely independent copy of an object, especially if it contains nested objects.
Essential for complex data structures to avoid unintended side effects.

Understanding deep and shallow copies is fundamental for JavaScript developers. It helps ensure data integrity and prevents bugs that arise from unintended shared references. By knowing when and how to use each type of copy, you can write more robust and maintainable code.

Top comments (1)

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy 🎖️ • Edited

For a deep copy, you can just use JavaScript's native structuredClone - no custom functions, playing with JSON encoding, or libraries required!

Some comments have been hidden by the post's author - find out more