Shallow Copy vs Deep Copy in JavaScript

When working with JavaScript, understanding the difference between shallow copy and deep copy is essential for effective manipulation of objects and arrays. Let’s delve into what these terms mean and how to implement each type of copy in your code.

Shallow Copy
A shallow copy creates a new object or array that holds the same values as the original. However, if the original contains nested objects or arrays, the shallow copy only copies the references to these nested structures, not the structures themselves. This means changes to the nested objects or arrays in the copied structure will also affect the original.

Examples of Shallow Copy Methods:

  1. Spread Operator ({…})
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
Enter fullscreen mode Exit fullscreen mode

Here, shallowCopy is a new object, but shallowCopy.b still references the same object as original.b.

2.Object.assign()

const shallowCopy = Object.assign({}, original);
Enter fullscreen mode Exit fullscreen mode
  1. Array slice Method
const originalArray = [1, 2, 3];
const shallowCopyArray = originalArray.slice();
Enter fullscreen mode Exit fullscreen mode

Deep Copy
A deep copy creates a new object or array that is a complete, independent clone of the original, including all nested objects and arrays. Changes to the deep copy do not affect the original and vice versa.

Examples of Deep Copy Methods:

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

This method serializes the object to a JSON string and then parses it back to a new object. However, it does not handle functions, undefined, or circular references.

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
  1. StructuredClone() (in modern JavaScript environments)
const deepCopy = structuredClone(original);
Enter fullscreen mode Exit fullscreen mode

When to Use Each

  • Shallow Copy: Suitable for simple objects or arrays without nested structures. It’s faster and uses less memory. Use it when you need a quick copy where changes to nested objects should reflect in both the original and the copy.

  • Deep Copy: Necessary for complex objects or arrays with nested structures. It ensures that changes to the copy do not affect the original. Use it when you need completely independent clones.

Understanding these differences helps prevent bugs that arise from unintended shared references and ensures data integrity in your applications


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top