var y = {a:200,b:{}};
console.log(y);
y.a = 100;
y.b[1] = 10;
y.b[2] = 20;
console.log(y);
Both the results on the console are same. Any idea why?
Result for line 2
Object {a: 200, b: Object} a: 100 b: Object 1: 10 2: 20
Result for Line 6
Object {a: 100, b: Object} a: 100 b: Object 1: 10 2: 20
console.log() has some funny behaviors in some browsers (I've seen it in Chrome) that probably has to do with the fact that console itself is in a different process and data has to get marshalled across a process boundary in the background (so it isn't done synchronously with your Javascript execution).
It appears that when you do something like console.log(y); and y is an object, what is immediately stored for the console is a reference to y and then sometime slightly later, the actual contents of y are fetched and displayed. But, if in the meantime your Javascript has modified y, then you won't necessarily get the exact right value for y displayed in the console.
You can work-around this issue by doing this:
console.log(JSON.stringify(y));
And, in fact you can test your code by changing both of your console.log() statements to this.
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