Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript pushing an object in an array is what - by reference or value?

When I create an object and push it to an array, is it stored by reference or value?

I see the following happening:

var abc = { a: 10, b: 20};
var def = [];
def.push(abc);

abc.a = 100;

def[0].a; // outputs 100!

// if I do this
abc = { a: 10000, b: 20000 };

def[0].a; // still 100, no change this time

Image from console:

Image from console

If I use the = sign to assign an object to abc, the reference pointed by abc in the array def should also change, isn't it?. What do we call above, by value or by reference?

I have understood it like abc is a reference pointing to a value. As long as we don't use = sign, it will keep pointing to that. Please guide.

like image 727
Om Shankar Avatar asked Sep 19 '25 05:09

Om Shankar


2 Answers

Let's have a look at what is happening:

var abc = { a: 10, b: 20};

A new object is created in memory and assigned to the variable abc.

var def = [];

A new array is created in memory and assigned to the variable def.

def.push(abc);

Inside the array there is now a pointer to the formerly created object.

 abc.a = 100;

 def[0].a; // outputs 100!

Obviously right. We are modifying the object, which is also referenced by the array.

 abc = { a: 10000, b: 20000 };

Again a new object is created and a reference to it is stored in abc. Now we have two objects (and an array) in memory.

 def[0].a; // still 100, no change this time

Of course, this is still 100. The array pointer still references the first created object and not the second one.

like image 92
Sirko Avatar answered Sep 20 '25 18:09

Sirko


Objects are ALWAYS passed by reference.

When you write abc = { a: 10000, b: 20000 }, what you are overwriting is the variable abc, which was pointing to the old object, but is now pointing to the new one.

like image 45
Niet the Dark Absol Avatar answered Sep 20 '25 18:09

Niet the Dark Absol