Shallow Copy and Deep Copy in JavaScript
Shallow Copy in JavaScript
When we use the spread operator (...) or methods like Object.assign() or slice() to copy an object or array, it creates a shallow copy.
This means only the top-level properties are copied, while nested objects or arrays are still referenced, not cloned.
🧪 Example with Array
Now both a and b are affected! That’s the problem with shallow copies — the nested values are shared by reference.
Deep copy solves the problem of modifying nested arrays without affecting the original array.
For example, when you have an array inside another array and you want to change the nested array, a deep copy ensures that changes don't affect the original data.
JSON.parse(JSON.stringify(array));
Array
let a = [1,2,[3,4]]
let b = JSON.parse(JSON.stringify(a));
b[2][1]= 300
console.log(b);
console.log(a);
Object
let a = {
name:"Ram",
street:{address1:"address1", adddress2:"address2" }
}
//let b = a;
let b = JSON.parse(JSON.stringify(a));
b.street.address1 = "Address1"
console.log(a);
console.log(b);
Comments
Post a Comment