Skip to main content

Command Palette

Search for a command to run...

Shallow Copy vs Deep Copy

Updated
•3 min read•View as Markdown
Shallow Copy vs Deep Copy
D

Hi, I'm Dikshant – a passionate developer with a knack for transforming ideas into robust, scalable applications. I thrive on crafting clean, efficient code and solving challenging problems with innovative solutions. Whether I'm diving into the latest frameworks, optimizing performance, or contributing to open source, I'm constantly pushing the boundaries of what's possible with technology.

On Hashnode, I share my journey, insights, and the occasional coding hack—all fueled by curiosity and a love for continuous learning. When I'm not immersed in code, you'll likely find me exploring new tech trends, tinkering with side projects, or simply enjoying a great cup of coffee.

Let's connect, collaborate, and build something amazing—one line of code at a time!

Let's break down shallow copy and deep copy in JavaScript using small exercises with input, comments, and explanations.


Understanding Shallow Copy vs Deep Copy

1. Shallow Copy

  • A shallow copy creates a new object, but it only copies references to nested objects.

  • Changes to nested objects in the copied version will affect the original.

2. Deep Copy

  • A deep copy creates a completely independent copy.

  • Changes in the copied object do not affect the original.


Exercise 1: Shallow Copy using Object.assign()

// Original object
let person = {
  name: "Rhea",
  age: 20,
  address: {
    city: "Mumbai",
    country: "India"
  }
};

// Creating a shallow copy using Object.assign()
let shallowCopy = Object.assign({}, person);

// Modifying the nested object
shallowCopy.address.city = "Pune";

console.log(person.address.city); // Output: "Pune" (original is affected)
console.log(shallowCopy.address.city); // Output: "Pune"

Explanation:


Exercise 2: Shallow Copy using Spread Operator (...)

// Using spread operator to create a shallow copy
let shallowCopy2 = { ...person };

// Modifying the nested object
shallowCopy2.address.city = "Delhi";

console.log(person.address.city); // Output: "Delhi" (original is affected)
console.log(shallowCopy2.address.city); // Output: "Delhi"

Explanation:

  • The spread operator { ...person } copies the top-level properties.

  • But nested objects (address) remain referenced, causing unintended side effects.


Exercise 3: Deep Copy using JSON.parse(JSON.stringify())

// Deep copy using JSON method
let deepCopy = JSON.parse(JSON.stringify(person));

// Modifying the nested object in deep copy
deepCopy.address.city = "Bangalore";

console.log(person.address.city); // Output: "Delhi" (original remains unchanged)
console.log(deepCopy.address.city); // Output: "Bangalore"

Explanation:

  • JSON.stringify(person) converts the object to a string.

  • JSON.parse() converts it back to an object, creating a new copy.

  • Changes to deepCopy do not affect person.

❗ Limitations:

  • Cannot copy functions or special objects like Date or Map.

Exercise 4: Deep Copy using structuredClone()

// Deep Copy using structuredClone (Modern method)
let deepCopy2 = structuredClone(person);

// Modifying the nested object
deepCopy2.address.city = "Hyderabad";

console.log(person.address.city); // Output: "Delhi" (original remains unchanged)
console.log(deepCopy2.address.city); // Output: "Hyderabad"

Explanation:

  • structuredClone() is a modern method that deeply copies objects, including arrays and nested structures.

  • It is more reliable than JSON.parse(JSON.stringify()).


Summary

MethodShallow/DeepCopies Nested Objects?Handles Functions/Date?
Object.assign()Shallow❌ (References only)✅ (Only top-level)
{ ...obj } (Spread)Shallow❌ (References only)✅ (Only top-level)
JSON.parse(JSON.stringify())Deep✅ (Creates new objects)❌ (Loses functions, Dates, etc.)
structuredClone()Deep✅ (Creates new objects)✅ (Handles special objects)

More from this blog

JavaScript_Learning

6 posts