Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is a variable stored as a memory refrence in javascript?

Tags:

javascript

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?

like image 327
Vivek Santhosh Avatar asked Dec 24 '22 08:12

Vivek Santhosh


2 Answers

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.

like image 126
Rajaprabhu Aravindasamy Avatar answered Dec 26 '22 20:12

Rajaprabhu Aravindasamy


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.

like image 37
Bergi Avatar answered Dec 26 '22 21:12

Bergi