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

let a = [10, 20, [30, 40]];
let b = [...a]; // Shallow copy

b[0] = 100;
console.log(a); // [10, 20, [30, 40]]
console.log(b); // [100, 20, [30, 40]]
Here, b is a shallow copy of a. When we change b[0], it doesnt affect the original. So far, so good.

But now, lets try changing the nested array


b[2][0] = 300;
console.log(a); // [10, 20, [300, 40]]
console.log(b); // [100, 20, [300, 40]]

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));







Example Deep copy 
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

Popular posts from this blog

Spread and Rest