Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript two-way reference issue

I am very confused about Javascript referencing. I understand when referencing an object, there is a reference made. Changing the parent changes the copy and vice versa.

What I am confused about is when reassignment changes are made to the parent, the copy retains everything. See my example

let tester = {
  "hello": "how are you",
  "myArrayHere": [
    { "id": 1, "name": "me" },
    { "id": 2, "name": "you" },
    { "id": 3, "name": "them" },
  ]
};

var something = tester.myArrayHere.find(x => x.name === "you");

console.log(something);
console.log("--------");

something.id = 99;
console.log(something);
console.log("--------");

console.log(tester.myArrayHere[1]);
console.log("--------");

tester.myArrayHere[1].id = 88;

console.log(something);
console.log("--------");

tester.myArrayHere[1] = {};
console.log(tester.myArrayHere[1]);
console.log("--------");

console.log(something)

If you run that example, something on the last line, still has the entire object, even though two lines above, its reference was re-assigned.

There are other examples of this, such as when you delete things off the parent, etc. If this is purely a reference and not a copy (such as with primitive types) why are these changes not affecting it as it should?

like image 981
KittenKiller Avatar asked May 17 '26 17:05

KittenKiller


1 Answers

The something variable simply refers to a (pre-defined) object stored in the memory. It's value is the returned value (a referral to an object) of the Array#find method. Variables do not observe any specific path (e.g. tester.myArrayHere[1]), they are not observers. In other words, in this case, JavaScript interpreter doesn't care/remember how you get the object/value before the assignment.

> var a, b; a = b = {};
> a === b
true
> a = {}
> a === b
false

After executing tester.myArrayHere[1] = {};, the second element of the array refers to a new object. The something variable still refers to the old object.

like image 75
undefined Avatar answered May 20 '26 06:05

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!