ShallowCopy
When we assign an object to another variable, JavaScript does not copy the actual data.
It copies the reference (memory address).
So both variables point to the same object.
Problem statement
let obj = {
name: "saurabh"
};
let user = obj;
name.name = "sachin";
console.log(obj); //output is sachin
Because obj and user refer to the same memory location.
Deep Copy
A shallow copy won't be enough if an object has nested objects (objects inside objects). That’s because a shallow copy only copies the top-level properties. The nested objects are still copied by reference.
So, if we change a value inside a nested object in the copied version, it will still affect the original object.
To avoid this, we use a deep copy, which copies everything, including all nested objects. This way, the copied object is completely separate from the original, and changes won’t affect each other.
Problem statement
let obj = {
name: "Saurabh",
address: {
city: "Pune",
state: "MH"
}
};
let user = {...obj}
user.address.city = "Mumbai"
console.log (obj) //output will be obj, city will be changed to Mumbai
Solution
let obj = {
name: "Saurabh"
address: {
city: "Pune"
State: "MH"
}
}
let user = JSON.parse(JSON.Stringfy(obj));
user.address.city = "Mumbai"
console.log(obj) // output remains the same as the obj will not change
Top comments (1)
Currently i'ts better use structuredClone to deepClone
developer.mozilla.org/en-US/docs/W...