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:

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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With