Chrome console don't show full object for console.log(obj); but only { a: {...} } - and when you click on "triangle" to show object content chrome console use actual object value.
StackOverflow snipped show full object content immediately on each iteration - but chrome only keep reference to object and look on him deeper only when user click on "triangle" in console.
You should make nested(deep) copy (popular way is for example JSON.parse(JSON.stringify(obj)) but you can find better ways on StackOverflow) of object at current loop iteration and give that deep copy to console.log(copyObj); . For example:
var obj = {
a: {
b: 0
}
}
for (i = 0; i < 10; i++) {
obj.a.b += 5;
console.log('log obj.a.b = ' + obj.a.b);
console.log( JSON.parse(JSON.stringify(obj)) );
}
After question update
The arr.push(obj) push only reference to the same object obj to array, use below code to add separate copy of obj (reference to copy to be precise) as new array element:
arr.push( JSON.parse(JSON.stringify(obj)) )
obj.a.b += 5;to the top ofconsole.log's as you did hereJSON.parse(JSON.stringify(obj));to properly get a "snapshot" of the object, by losing the reference to the original one (arrays are objects, in javascript). That said, simply push a new copy of the object to avoid reference issues, like this: jsfiddle.net/m4pqxo1d/4Object.assign({}, obj)is for shallow object copy - in your benchmark you use it for deep copy (which is not good because - for large object you will need to write a lot of code). On stack overflow you can find alternative apprach to object deep copy e.g here stackoverflow.com/q/122102/860099.