3
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
  • 3
    The console always shows you the current state of an object, it doesn't capture the state as it was when logged. Put a `debugger;` after the first log to see the difference. – Evan Trimboli Nov 09 '15 at 04:00

2 Answers2

3

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • After writing this answer, I found a [duplicate question](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) and marked the question as such. – jfriend00 Nov 09 '15 at 04:16
0

Using console.log prints your object to console via reference, you can log the current state of the object by converting it to JSON as an alternative.

console.log(JSON.stringify(y));
Tim Sheehan
  • 3,994
  • 1
  • 15
  • 18