I was exploring about shallow copy and deep copy and got little confused here. What I understood till now was, in a deep copy the reference value of two objects differs and on mutating one object doesn't induce any change in the other object, whereas in a shallow copy objects share the same reference value and thus both objects get mutated if any one of them gets mutated.
Here is my sample code :
// a multinested array A
const A = [10, 20, [100], 30];
const B = [...A] ;
console.log( Object.is(A, B) );
console.log( A === B ) ; // both arr objects have diff reference
B[2].push(200) ;
console.log('arr A: ' , A) // logs [10, 20, [100, 200], 30]
console.log('arr B: ' , B) // also logs [10, 20, [100, 200], 30]
While testing with '===' operator it gives false which means array A and B don't share same reference gives out false as expected since both arrays have different reference value.
But when I push an element inside the inner array of array B B[2].push(200) ;
array A also gets mutated.
If we created a deep copy using spread operator then why did array A also get mutated ?
On the contrary when I used B.push(200) ;
instead of B[2].push(200) ;
then array A doesn't gets mutated.
// a multinested array A
const A = [10, 20, [50, 100], 30];
const B = [...A] ;
console.log( Object.is(A, B) );
console.log( A === B ) ; // both arr objects have diff reference
B.push(200) ;
console.log('arr A: ' , A) // logs [10, 20, [50, 100], 30]
console.log('arr B: ' , B) // also logs [10, 20, [50, 100], 30, 200]
Why does array A gets mutated in the former case whereas it doesn't in the latter case ?