Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained
When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These concepts dictate how data is duplicated and whether changes to the copied data affect the original.
1. Shallow Copy
A shallow copy duplicates an object's first level properties. However, if the object contains references (like nested objects or arrays), the references themselves are copied—not the values they point to. This means changes to nested properties in the copied object will reflect in the original.
Example:
const original = {
name: "Alice",
address: {
city: "Wonderland",
zip: "12345"
}
};
// Creating a shallow copy
const shallowCopy = { ...original };
// Modifying the nested object
shallowCopy.address.city = "Looking Glass";
// Both objects are affected
console.log(original.address.city); // Output: "Looking Glass"
console.log(shallowCopy.address.city); // Output: "Looking Glass"
Methods to Create Shallow Copies:
- Using the spread operator (...
):
const shallowCopy = { ...originalObject };
- Using Object.assign()
:
const shallowCopy = Object.assign({}, originalObject);
2. Deep Copy
A deep copy duplicates all properties, including nested objects and arrays. It creates entirely independent objects, ensuring changes to the copy do not affect the original.
Example:
const original = {
name: "Alice",
address: {
city: "Wonderland",
zip: "12345"
}
};
// Creating a deep copy
const deepCopy = JSON.parse(JSON.stringify(original));
// Modifying the nested object
deepCopy.address.city = "Looking Glass";
// Only the copy is affected
console.log(original.address.city); // Output: "Wonderland"
console.log(deepCopy.address.city); // Output: "Looking Glass"
Methods to Create Deep Copies:
Using
JSON.stringify()
andJSON.parse()
:- Converts the object to a JSON string and back.- Limitations: - Does not handle circular references. - Ignores non-JSON-safe data like functions,undefined
,Symbol
, etc.Using a Custom Recursive Function:- Write a function to recursively copy properties.
Using Libraries:
- Popular libraries like Lodash provide deep cloning methods:
const _ = require("lodash");
const deepCopy = _.cloneDeep(originalObject);
Key Differences
Feature | Shallow Copy | Deep Copy |
Nested References | Retained (shared with the original) | Fully duplicated (independent) |
Performance | Faster | Slower (due to recursion or iteration) |
Usage | Simple structures | Complex or deeply nested structures |
When to Use Which?
Shallow Copy:- When working with flat objects or when changes to nested data are intentional.- Example: Copying configuration objects with minimal nesting.
Deep Copy:
- When dealing with deeply nested objects and ensuring independence is critical.
- Example: Cloning application state in Redux or immutability in React.
Understanding and choosing the right approach helps avoid bugs and unintended side effects in your JavaScript applications.
Please login or create new account to add your comment.