Introduction
Copying objects and arrays is a common task in JavaScript. However, understanding the difference between shallow copy and deep copy is crucial to avoid unintended side effects in your applications. In this blog, we’ll explain these concepts, their differences, and how to implement both with examples.
What is a Shallow Copy?
A shallow copy duplicates only the first level of properties of an object or array. If the object contains nested objects, only references to those nested objects are copied.
Example of a Shallow Copy
const original = { name: "John", address: { city: "New York" } };
const shallowCopy = { ...original };
shallowCopy.name = "Jane"; // Changes only the shallowCopy
shallowCopy.address.city = "Los Angeles"; // Changes both original and shallowCopy
console.log(original.address.city); // Output: "Los Angeles"
Methods for Shallow Copy
- Spread Operator (
**...**
):
const copy = { ...original };
const arrayCopy = [...originalArray];
- Object.assign():
const copy = Object.assign({}, original);
What is a Deep Copy?
A deep copy duplicates all levels of an object or array, creating a completely independent clone. Changes in the copied object do not affect the original object, even for nested objects.
Example of a Deep Copy
const original = { name: "John", address: { city: "New York" } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.name = "Jane"; // Changes only the deepCopy
deepCopy.address.city = "Los Angeles"; // Changes only the deepCopy
console.log(original.address.city); // Output: "New York"
Methods for Deep Copy
**JSON.parse(JSON.stringify())**
:- Works for simple objects but fails for functions,
undefined
, or circular references.
- Works for simple objects but fails for functions,
const deepCopy = JSON.parse(JSON.stringify(original));
- Lodash Library (
**_.cloneDeep**
):- Handles complex cases effectively.
const _ = require("lodash");
const deepCopy = _.cloneDeep(original);
- Custom Recursive Function:
- Write your own function for specific needs.
function deepCopy(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
const copy = Array.isArray(obj) ? [] : {};
for (const key in obj) {
copy[key] = deepCopy(obj[key]);
}
return copy;
}
Key Differences Between Shallow Copy and Deep Copy
Feature | Shallow Copy | Deep Copy |
---|---|---|
Copies nested objects? | No | Yes |
Affects original data? | Yes (for nested objects) | No |
Performance | Faster | Slower |
Methods | Object.assign() , ... | JSON.parse(JSON.stringify()) , _.cloneDeep() |
When to Use Each?
- Shallow Copy:
- When the object is flat (no nested structures).
- When performance is critical, and nested object changes are acceptable.
- Deep Copy:
- When working with deeply nested objects.
- When you need complete independence between the original and the copied data.
Conclusion
Understanding the difference between shallow and deep copies in JavaScript is essential for effective programming. Use shallow copies for simple objects and deep copies when working with nested data to avoid unexpected behavior. By choosing the right approach, you can ensure your application behaves as expected.
Happy coding! 🚀