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.
Written by Wenson Smith
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Array
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#