Reputation: 299
I have read that a variable is stored as a memory reference in js.
So for var a = 5
, the memory location with value 5
is assigned to a
.
I tried running this on node.js:
var a = 5;
var b = {
val: a
};
a = 6;
I expect b.val
to be 6
but is 5
,
If I run:
var a = 5;
var b = {
val: a
};
var c = {
value: b
}
b.val = 6;
Than c.value.val
is 6
.
If they are all memory objects, why is there a difference in outputs?
Upvotes: 4
Views: 370
Reputation: 67207
In javascript when you assign an object
to another variable
, its memory reference
will be shared. It will not create a copy. At the same time, primitive values
will act exact opposite to that. It will create a copy when it got assigned to another one variable
.
Also you have to note about this odd situation,
var x = { a: 10 };
var y = x;
x = 5;
At a first look, after hearing a basic explanation about objects, everyone(new learners) would tell that, y
will contain 5
. But that is wrong. y
will have the older value, that is {a:10}
. Because at this context, x
's old reference will be cut off and new value will be assigned with new memory location. But Y
will hold its reference that was given by x
.
Upvotes: 8
Reputation: 664406
I have read that a variable is stored as a memory reference in js.
Well, yes, all variables are basically references to memory - in all languages.
So for
var a = 5
, the memory location with value 5 is assigned to a.
I would say "the value 5
is written to the memory location with the name a
".
I expect b.val to be 6 but is 5
How so? … val: a …
means "take the value from the memory location with the name a
and create a property named val
with it. The value that is stored there is 5
.
In JavaScripts, only objects are values that reference more memory (specifically, their respective properties), and passing around such a reference value will always reference the same set of properties (the "object"). All other values - so called primitive values - are just immutable values, no references.
Upvotes: 2