'Is the parent object reference changed if a child object is changed?
Suppose I have this
let a = { data: 'old' }
Lets say hypothetically that a has a reference to '123'
If I do
a.data = 'new'
Is the reference of a still pointing to '123' or has it been reallocated?
Thank you
Solution 1:[1]
You can make a very simple test for this:
let a = { data: "something" };
let b = a;
Now a and b are references to the exact same object.
a.data = "something else";
console.log(a === b); // true
Assigning to the property does not affect the value of a. Also:
console.log(b.data); // "something else"
Solution 2:[2]
Hypothetically, if a points to '123', you can assume that a.data points to '456'.
a->123
a.data -> 456
Now when you change a.data to "new" (say now at 789), you change the pointer for a.data so a would continue to point to the old value.
a->123
a.data->789
ReactJS specific: This is the reason why when dealing with object states, react may not re-render if you change a deep object key because the parent reference does not change.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pointy |
| Solution 2 | Aneesh |
