I wish to understand the following behaviour when pushing objects into an array.
(1) I create an object, create a property of the object and then push it into an array.
var array = [];
var obj = {};
obj.x = 1;
array.push(obj);
console.log(array); //Output [{x: 1}]
Consider the two alternatives:
(2a): I change the object's property and so change the object referenced in the array:
obj.x = 2;
console.log(array); //Output [{x: 2}] ... it has been changed
(2b instead of 2a) I make the object reference refer to a new object and create the property, the original object referenced in the array is unchanged:
obj = {}; //Change reference to new object
obj.x = 2;
console.log(array); //Output [{x: 1}] ... it is unchanged
Why is this the case?
P.S: I notice that this distinction is discussed here (Do objects pushed into an array in javascript deep or shallow copy?), but it is not satisfactorily explained.