Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior with objects & console.log [duplicate]

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?

like image 224
dan-klasson Avatar asked May 02 '14 13:05

dan-klasson


1 Answers

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.

For example, Chrome will show 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:

console.log(obj.foo, obj.bar, obj.baz); 

Or JSON encode the object reference:

console.log(JSON.stringify(obj)); 
like image 106
zzzzBov Avatar answered Oct 14 '22 17:10

zzzzBov