obj
and copiedObj
are arrays, not plain objects. Changing the state of copiedObj
(by adding a checked
property to it) does not change the state of obj
because they're separate arrays.
But, both of the arrays contain a reference to the same object (the one with cheecked
on it). So if you did:
checkedObj[0].checked = true;
that would change the state of that one object, which you would see whether you looked up that object on obj[0]
or checkedObj[0]
.
If you want to make a deep copy so that you have separate arrays and separate objects, see this question's answers.
Since I'm 99% sure you meant checkedObj[0].checked = true
, I'll explain what's happening in this code:
// Creates an array containing an object
const obj = [{id: 1, checked: true}];
// Creates a new array that contains the *same* object (NOT a *copy* of it)
const copiedObj = [...obj];
// Sets `checked` on that one object that is in both arrays
copiedObj[0].checked = false;
// Looks at the `checked` property on that one object that is in both arrays
console.log(obj[0].checked);
Step by step:
After
// Creates an array containing an object
const obj = [{id: 1, checked: true}];
in memory you have something like
+−−−−−−−−−−−−−+
obj:Ref44329−−−−−>| (array) |
+−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+
| 0: Ref82445 |−−−>| (object) |
+−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+
| id: 1 |
| checked: true |
+−−−−−−−−−−−−−−−+
Then when you do
// Creates a new array that contains the *same* object (NOT a *copy* of it)
const copiedObj = [...obj];
you have something like:
+−−−−−−−−−−−−−+
obj:Ref44329−−−−−−−−−−>| (array) |
+−−−−−−−−−−−−−+
| 0: Ref82445 |−−+
+−−−−−−−−−−−−−+ |
|
| +−−−−−−−−−−−−−−−−+
+−−>| (object) |
+−−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−−−+
checkedObj:Ref12987−−−>| (array) | | | id: 1 |
+−−−−−−−−−−−−−+ | | checked: true |
| 0: Ref82445 |−−+ +−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−+
Then when you do
// Sets `checked` on that one object that is in both arrays
copiedObj[0].checked = false;
it changes the object that both arrays point to
+−−−−−−−−−−−−−+
obj:Ref44329−−−−−−−−−−>| (array) |
+−−−−−−−−−−−−−+
| 0: Ref82445 |−−+
+−−−−−−−−−−−−−+ |
|
| +−−−−−−−−−−−−−−−−+
+−−>| (object) |
+−−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−−−+
checkedObj:Ref12987−−−>| (array) | | | id: 1 |
+−−−−−−−−−−−−−+ | | checked: false |
| 0: Ref82445 |−−+ +−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−+
...so looking it up will give you false
regardless of which array you look at it through.