here’s an experiment I made:
const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const copyArray = array;
copyArray[0].id = 5;
console.log(“array”, array, “copyArray”, copyArray);
array and copyArray have the same result because they’re both pointing at the very same object.
now see what happens when I use the spread operator:
const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const copyArray = [...array];
copyArray[0].id = 5;
console.log("array", array, "copyArray", copyArray);
In this example the result will again be the same because although I used the spread operator on the array still the object at each index is the same, whereas if I give it a different object completely only copyArray will get changed and array will remain unchanged as follows:
const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const copyArray = […array];
copyArray[0] = 5;
console.log(“array”, array, “copyArray”, copyArray);
In order to make a change to that object I would have to use the spread operator again as follows:
const array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const copyArray = [...array];
copyArray[0] = { ...array[0] };
copyArray[0].id = 5;
console.log("array", array, "copyArray", copyArray);
Finally, I get array = [{ id: 1 }, { id: 2 }, { id: 3 }] and copyArray = [{ id: 5 }, { id: 2 }, { id: 3 }].
Hope this is helpful!