Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

primitive types / reference types in Javascript

Tags:

javascript

I have lived under the assumption that there are primitive types and reference types in Javascript. On a day-to-day basis, I've never had this impact me but I was just starting to a lot more JS and wanted to update my 'thinking'. In other words, I would have betted $20 that the following would return 68

var my_obj = {};
var tmp_obj = {};

tmp_obj.my_int = 38;
my_obj.tmp_val = tmp_obj.my_int;
tmp_obj.my_int = 68;

alert('68 means reference, 38 means primitve: ' + my_obj.tmp_val);

but it returns 38.

enter image description here

Are all instances of numbers primitive types even if they exist in the context of a reference type? If y, I'm really surprised and find that odd behavior(and would be out $20). Or is my example not demonstrating what I think it is?

thx in advance

UPDATE #1

Wow, thx for all the answers. Here's a slight change which helps me a lot in understaning:

var my_obj={};
var tmp_obj={};
var my_obj_2=tmp_obj;
tmp_obj.my_int=38;
my_obj.tmp_val=tmp_obj.my_int;
tmp_obj.my_int=68
alert('68 means reference, 38 means primitve: ' + my_obj.tmp_val);   // 38
alert('68 means reference, 38 means primitve: ' + my_obj_2.my_int);  // 68
my_obj_2.my_int=78;
alert(tmp_obj.my_int); // tmp_obj is now 78 ie two way
like image 231
timpone Avatar asked Jan 21 '13 16:01

timpone


2 Answers

You example would work as expected if you had

     my_obj = tmp_obj;

Then, all the properties would point to the same reference since there would only be one object.

But when you write

     my_obj.tmp_val = tmp_obj.my_int;

then my_obj.tmp_val will take the value that's stored in tmp_obj.my_int but that doesn't create a new reference between the 2 objects.

like image 73
frenchie Avatar answered Oct 12 '22 12:10

frenchie


Yes, values like numbers and strings work like primitive values. They are immutable. Assigning a new value to a variable replaces the old value, it doesn't change the value that's there.

Example:

var x = 42;
var y = x; // y == 42
x = 1337; // this puts a new value in x, it doesn't change 42 to be 1337
alert(y); // it's still 42

The same works for strings:

var x = "42";
var y = x; // y == "42"
x = "1337"; // this puts a new string in x, it doesn't change "42" to be "1337"
alert(y); // it's still "42"

Also if you use object properties;

var o = {};
o.x = 42;
o.y = o.x; // o.y == 42
o.x = 1337; // this puts a new value in o.x, it doesn't change 42 to be 1337
alert(o.y); // it's still 42

How a value acts only depends on its type, not wether it's stored in a regular variable or in a property in an object.

Even if strings are implemented as an object internally, it's immutable and works as a value. Copying a string may copy a reference to an object, but the effect is that you get a separate copy, because nothing can change the string value itself.

like image 39
Guffa Avatar answered Oct 12 '22 12:10

Guffa