I like to think I have and understanding of reference types, but I am wondering what I am missing here, what is happening under the hood.
let o = {
foo: 'bar'
};
console.log(o) // logs the object.
let p = o; // assigns reference to object
I have seen this a thousand times and move on without a thought, but this time it gave me an unexpected psychedelic jolt.
In both cases my mind reads this as 'read the value of o and'. However, one will log the actual data stored whereas the other will return a reference. What step am I missing that makes these two lines differ?
is let p = o;
how things normally work, but
console.log(o)
is causing some type of implicit / default call.
Or is it the inverse, that o
will naturally pull the actual object
from the heap but an assignment will by nature always assign the
reference?
"when x JavaScript will z"
Can someone explain the workings of this so I understand the exact why of it?
If you copy the value, then you copy a reference to the object.
If you do anything else with it, then the reference is followed and the object worked with.
The value of o
is a reference to an object.
If you assign o
to p
then you copy that reference and p
is also a reference to the object.
If you access o.foo
then you follow the reference to the object and do something with the foo
property of it.
If you pass o
to a function, then you copy the reference to the parameter in the function. If that function then accesses paramater.foo
then it follows the reference to the object and does something with the value of foo
on it.