Deep copy vs Shallow copy in Javascript

ยท

2 min read

JavaScript provides different ways to copy objects and arrays, but not all copies behave the same way. The main distinction lies between shallow copy and deep copy. In this blog, we will explore both concepts with practical examples and best practices.

What is a Shallow Copy?

A shallow copy creates a new object that contains references to the original object's nested objects instead of duplicating them. This means that changes made to the nested objects in the copy will reflect in the original object.

Example of Shallow Copy

const obj1 = {
  name: "Siraj",
  details: { age: 25, city: "Mumbai" }
};

// Creating a shallow copy using spread operator
const obj2 = { ...obj1 };

obj2.name = "Shaikh"; // Only changes obj2's name
obj2.details.city = "Pune"; // Modifies obj1 as well!

console.log(obj1.details.city); // Output: "Pune" (Original object is affected!)
console.log(obj2.details.city); // Output: "Pune"

Ways to Create a Shallow Copy

  • Spread Operator (...)

  • Object.assign({}, obj)

  • Array.prototype.slice() (for arrays)


What is a Deep Copy?

A deep copy creates a completely independent copy of the object, including all nested objects. Changes to the copy do not affect the original object.

Example of Deep Copy

const obj1 = {
  name: "Siraj",
  details: { age: 25, city: "Mumbai" }
};

// Creating a deep copy using JSON methods
const obj2 = JSON.parse(JSON.stringify(obj1));

obj2.details.city = "Pune"; // Changes only obj2

console.log(obj1.details.city); // Output: "Mumbai" (Original object remains unchanged)
console.log(obj2.details.city); // Output: "Pune"

Ways to Create a Deep Copy

  1. JSON.parse(JSON.stringify(obj)) (Does not support functions, undefined, or special objects like Date)

  2. structuredClone(obj) (Best modern approach)

  3. Lodash _.cloneDeep(obj) (Using Lodash library)

  4. Recursively copying objects manually


Key Differences Between Deep Copy and Shallow Copy

FeatureShallow CopyDeep Copy
Nested ObjectsCopied by reference (not duplicated)Fully copied (new independent object)
Original Object ChangesAffects copied objectNo effect on copied object
Methods..., Object.assign(), Array.slice()JSON.parse(JSON.stringify()), structuredClone(), _.cloneDeep()

When to Use Which?

  • Use a Shallow Copy when working with simple objects that do not contain nested objects.

  • Use a Deep Copy when you need to ensure that changes in the copied object do not affect the original one.

By understanding deep and shallow copies, you can write more efficient and bug-free JavaScript code. ๐Ÿš€

ย