Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bizarre console.log behaviour in Chrome Developer Tools [duplicate]

Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?

Open up Chrome Developer Tools and type in:

var a = [];console.log(a);a.push(1);console.log(a);

You would expect this to output something like

[]
[1]

But instead it outputs

[1]
[1]

The behaviour is the same for

var a = [];console.log(a);a[0] = 1;console.log(a);

Can anyone explain this behaviour?

Running Chrome on OS X. Same behaviour on 32bit Windows 7.

EDIT: The behaviour is the same regardless of whether the statements are on the same line or not. I have simply provided them on a single line to make it easy to test.

Putting

var a = [];
console.log(a);
a.push(1);
console.log(a);

in a file then running it yields the same behaviour.

EDIT x 2 See: http://jsfiddle.net/9N4A6/ if you don't feel like making a file to test.

like image 318
Jamie Wong Avatar asked Nov 16 '10 21:11

Jamie Wong


3 Answers

Try this instead:

var a = []; console.log(a.toString()); a.push(1); console.log(a.toString());

It's not that the order of evaluation is strange, I bet, but that the conversion of the objects to printable form happens after the statements are all executed, at the point when Chrome is ready to actually dump out the log.

like image 140
Pointy Avatar answered Nov 07 '22 10:11

Pointy


Same behavior here with Win7 on a x64 machine. My guess is that the log method holds a reference to a and queues the calls that happen to be in a single line.

EDIT It's not a Chrome/ium issue alone, I have witnessed the same with Firebug. As I said console logging must be queued in some ways.

like image 3
aefxx Avatar answered Nov 07 '22 11:11

aefxx


What's being "logged" is the object "a"... not the plain text representation of "a". The log display is clever enough to display a place holder for object "a", which gets filled in/populated "later" (seems like at the end of the event invocation). If you stick an alert() statement in you'll see the values you expect (logged values get "filled in"):

var a = [];
console.log(a);
alert('force console to display correctly');
a.push(1);
console.log(a);

This seems like a bug in Chrome to me (kinda goofy to have to put an alert statement in to see the correct logging information).

(note this question showed at the top of a google search for "console.log chrome only shows current values" so I thought I'd add my answer)

like image 3
user505765 Avatar answered Nov 07 '22 12:11

user505765