Copy is the same value as anything. But copy value and the original value have individual independence. That means if the copy value is changed, the original value doesn't change according to the copy value.
Deep copy: Deep copy copies the value of the original value and disconnects with the original value. A deep copy copies the old value and allocates a different memory location for the new copy. Then assign the old value to the new variable or object.
Now, if we change the value of b=6
, then the value of a
is not changed.
let a = 5;
let b = a;
b = 6;
console.log(b)//6
console.log(a);//5
If we change the value of a
, then the value of b
is not changed.
let a = 5;
let b = a;
a = 6;
console.log(b) //5
console.log(a); //6
Shallow copy: Shallow copy means a new value is connected to the original value. In memory, the new object has stored the location of the original object. This is the reason, the copy object and original object are dependent on each other. If the state of the copy or original object is changed, it reflects in both.
a = {
name: "John",
age: 30
}
b = a;
a.name = "Peter";
console.log(b.name);// Peter
Now, look at the above code. When we change the value of a.name
, b.name
is also changed. This is the shallow copy.
Think for a couple of minutes, what if we changed the value of b.name
, what is happened to the a.name
. Is it changed or not?
a = {
name: "John",
age: 30
}
b = a;
b.name = "Peter";
console.log(a.name);// Peter
Shallow copy is like nibba/ nibbi lovers. If you hit one, another one also feels the pain ๐.
Now, the big question is how to deep copy an object? Spread operator in JavaScript saves you in this situation.
const a = {
name: "John",
age: 30
}
let b = { ...a };
b.name = "Peter";
console.log(a.name);// Jhon
But there is a little problem with nested objects.
const a = {
name: "John",
age: 30,
address: {
city: "New York",
}
}
let b = { ...a };
b.address.city = "London";
console.log(a.address.city);// London
This behaves like a shallow copy. Now how to solve this problem?
const a = {
name: "John",
address: {
city: "New York",
}
}
let b = { ...a, address: { ...a.address } };
b.address.city = "London";
console.log(a.address.city);// New York
Huuh! We solved nested object problems like this.