The difference between Shallow & Deep Copy.

Today, I am going to disscuss about the Shallow copy and deep copy. I hope if you read this article, you can get better idea about it.
Just imagine you have an Object like this.
const original = { name: "Ahmad", address: { city: "Gujrat" } };
Shallow Copy (Reference to Original)
Modifying a nested object in the shallow copy will also modify it in the original object because they share the same reference.
When to Use
- Simple Objects: When dealing with simple objects that do not contain nested objects, a shallow copy is sufficient and more efficient.
- Performance Consideration: When you want a quick copy and you know that the nested objects won’t change or don’t need to be independent of the original.
- Immutable Top-Level Properties: If you’re only updating or modifying the top-level properties and are not concerned with nested objects.
What to Use
- Spread Operator (
...
): Commonly used for shallow copying in JavaScript due to its simplicity and readability. Object.assign()
: Another way to create a shallow copy, especially when you want to merge objects.
// Original object
const original = { name: "Ahmad", address: { city: "Gujrat" } };
// Shallow copy using spread operator
const shallowCopy = { ...original };
// Modifying the shallow copy
shallowCopy.address.city = "Lahore";
// Result
console.log(original.address.city); // Output: "Lahore" (because shallow copy modified the original)
console.log(shallowCopy.address.city); // Output: "Lahore"
Deep Copy (New Independent Object)
Modifying any part of the deep copy does not affect the original object at all, because the deep copy is entirely separate.
When to Use
- Complex Objects: When the object contains nested structures, and you need an independent copy that won’t affect the original object.
- Avoiding Side Effects: When you need to ensure that changes to a copy of an object do not affect the original, especially in large or complex applications.
- Immutable Nested Properties: If the nested objects need to be modified independently of the original.
What to Use
JSON.parse(JSON.stringify())
: A common method for deep copying, but it has limitations (e.g., it doesn’t handle functions,undefined
, orDate
objects well).- Libraries like
lodash
(_.cloneDeep
): More reliable for deep copying complex objects, especially when dealing with various data types.
// Original object
const original = { name: "Ahmad", address: { city: "Gujrat" } };
// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));
// Modifying the deep copy
deepCopy.address.city = "Karachi";
// Result
console.log(original.address.city); // Output: "Gujrat" (deep copy is independent and didn't affect the original)
console.log(deepCopy.address.city); // Output: "Karachi"
Thanks for reading the article. I hope you now have a better understanding of shallow copy and deep copy concepts.