Deep Copy vs Shallow Copy in JavaScript
Sidhartha Mallick
Posted on January 5, 2022
Shallow Copy
A new object is created that has an exact copy of the values in the original object. If the original object points to another object, a separate copy of that object is not created, rather a reference to that object is passed.
const a = {
name: 'S. Sahu',
addr: {
city: 'Behrampur',
}
}
const b = {...a}; // shallow copy using spread operator
b.addr.city = "Sambalpur"; // Shallow Copy
b.name = "A. Panda"; // Deep Copy
console.log(a.name, b.name); // separate references for name is created here
console.log(a.addr, b.addr); // a.addr and b.addr point to the same object reference
Output:
Sambalpur Sambalpur
S. Sahu A. Panda
Deep Copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
const a = {
name: 'S. Sahu',
addr: {
city: 'Behrampur',
}
}
const b = {
name: a.name,
addr: {
city: a.city
}
};
b.addr.city = "Sambalpur";
b.name = "A. Panda";
console.log(a.addr.city, b.addr.city);
console.log(a.name, b.name)
Output :
Behrampur Sambalpur
S. Sahu A. Panda
Create Reference
A reference of the original object is created. Any changes made in the new object is reflected in the original object.
const a = {
name: 'S. Sahu',
addr: {
city: 'Behrampur',
}
}
const b = a;
b.addr.city = "Sambalpur";
b.name = "A. Panda";
console.log(a.addr.city, b.addr.city);
console.log(a.name, b.name)
Output :
Sambalpur Sambalpur
A. Panda A. Panda
💖 💪 🙅 🚩
Sidhartha Mallick
Posted on January 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.