Last Updated: February 25, 2016
·
5.434K
· wensonsmith

Javascript Array push Object by reference

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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside