‘a’ array wasn’t affected.
const a = [1,2,3]
const b = [...a] // shallow copy
b[0] = 9
console.log(a) // [1,2,3]
console.log(b) // [9,2,3] results as expected
----------
const a = [{name:"John"},{name:"George"}];
const b = [...a];
b[0] = {name:"Oliver"}
console.log(a) // [ { name: 'John' }, { name: 'George' } ]
console.log(b); // [ { name: 'Oliver' }, { name: 'George' } ] results as expected
----------
const a = [{name:"John"},{name:"George"}];
const b = [...a];
b[0].age = 21
console.log(a); //[ { name: 'John', age: 21 }, { name: 'George' } ]
console.log(b); // [ { name: 'John', age: 21 }, { name: 'George' } ]
// why were affected ‘a’ array ?
Why were they both affected? It shows the same reference, but in the other 2 examples above, there was no change, only the ‘b’ array changed.
Kaan Topal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
It happens because the reference of the object is not changing, internally when you make a shallow copy of the “a” array, you are making a copy of a reference to those objects, so after changing b[0] object you are also affecting a[0] since its the same object
Andres Contreras Vargas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.