Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Updating copied object also updates the parent object in JavaScript?
When copying objects in JavaScript, understanding shallow vs deep copying is crucial. Simply assigning an object creates a reference, not a true copy, which can lead to unexpected behavior where modifying the "copy" also updates the original.
The Problem with Direct Assignment
Direct assignment creates a reference to the same object in memory:
var original = { name: 'John', age: 30 };
var copy = original; // This creates a reference, not a copy
copy.name = 'Smith';
console.log("Original:", original);
console.log("Copy:", copy);
Original: { name: 'Smith', age: 30 }
Copy: { name: 'Smith', age: 30 }
Using Object.assign() for Shallow Copying
Object.assign() creates a shallow copy, preventing changes to the copy from affecting the original:
var firstObject = { name: 'John' };
var secondObject = { name: 'Carol' };
console.log("Before merging:");
console.log(firstObject);
var afterMerging = Object.assign({}, firstObject, secondObject);
afterMerging.name = 'Smith';
console.log("After merging and modifying copy:");
console.log("Original:", firstObject);
console.log("Modified copy:", afterMerging);
Before merging:
{ name: 'John' }
After merging and modifying copy:
Original: { name: 'John' }
Modified copy: { name: 'Smith' }
Shallow vs Deep Copying
Object.assign() only performs shallow copying. For nested objects, references are still shared:
var original = {
name: 'John',
address: { city: 'New York', country: 'USA' }
};
var shallowCopy = Object.assign({}, original);
shallowCopy.address.city = 'Los Angeles';
console.log("Original city:", original.address.city);
console.log("Copy city:", shallowCopy.address.city);
Original city: Los Angeles Copy city: Los Angeles
Alternative Copying Methods
| Method | Type | Nested Objects |
|---|---|---|
Object.assign() |
Shallow | Shared references |
Spread operator (...) |
Shallow | Shared references |
JSON.parse(JSON.stringify()) |
Deep | True copies |
Using Spread Operator
var original = { name: 'John', age: 30 };
var copy = { ...original };
copy.name = 'Smith';
console.log("Original:", original);
console.log("Copy:", copy);
Original: { name: 'John', age: 30 }
Copy: { name: 'Smith', age: 30 }
Conclusion
Object.assign() and spread operator create shallow copies that don't affect the parent object. For nested objects, consider deep copying techniques to ensure complete independence between original and copy.
