dan-klasson dan-klasson - 1 month ago 12
Javascript Question

Weird behavior with objects & console.log

This code:

foo = [{id: 1},{id: 2},{id: 3},{id: 4}, {id: 5}, ];
console.log('foo1', foo, foo.length);
foo.splice(2, 1);
console.log('foo2', foo, foo.length);


Produces the following output in Chrome:

foo1
[Object, Object, Object, Object, Object] 5
0: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]
5 (index):23
foo2
[Object, Object, Object, Object] 4
0: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]


Fiddle: http://jsfiddle.net/2kpnV/

Why is that?

Answer

Examining objects via console.log happens in an asynchronous manner. The console receives a reference to the object synchronously, but does not display the properties of the object until it is expanded (in some cases, depending on the browser and whether you have dev tools open when the log happens). If the object has been modified before examining it in the console, the data shown will have the updated values. (Chrome, for one, shows a little i in a box which, when hovered, says "Object value at left was snapshotted when logged, value below was evaluated just now." to let you know what you're looking at.)

One trick for logging in these cases is to log the individual values, or JSON encode the object reference:

console.log(obj.foo, obj.bar, obj.baz);
//or
console.log(JSON.stringify(obj));