Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between assigning value to variable and storing value into variable

Tags:

javascript

oop

I was reading a book about object oriented javascript and I found this:

Reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory where the object exists. This is the primary difference between objects and primitive values, as the primitive is stored directly in the variable.

My question is what is the meaning of this ?

"Reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance." ??

enter image description here

like image 538
Aniruddha Chakraborty Avatar asked Feb 20 '26 13:02

Aniruddha Chakraborty


1 Answers

In the image you provided you can see

var object1 = new Object();
var object2 = object1;

In this case, you have two variables that both store a reference (think of a pointer) to another place in your memory. In this place the object is stored. If you change your object via one of the references, and access it via the other one you will see it has changed.

object1.someVariable = 'asdf';
object2.someVariable = 'newValue';
console.log(object1.someVariable); // will give 'newValue'
console.log(object2.someVariable); // will also give 'newValue'

If you have scalar values, they will not store references, they will store the value itself.

Think of another example:

var primitiveString = 'asdf';
var anotherPrimitiveString = primitiveString;

Since both store the value it self, you can change one of the two strings, but the other one will still contain asdf, since they do not reference something.

anotherPrimitiveString = 'newValue';
console.log(primitiveString); // will give 'asdf'
console.log(anotherPrimitiveString); // will give 'newValue'

Here you have a jsfiddle with the explained example.

like image 151
bpoiss Avatar answered Feb 23 '26 03:02

bpoiss



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!