Is Chrome'S JavaScript Console Lazy About Evaluating Objects

Is Chrome’s JavaScript console lazy about evaluating objects?

Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 (EDIT: now fixed!)

There appears to be some debate regarding just how much of a bug it is and whether it's fixable. It does seem like bad behavior to me. It was especially troubling to me because, in Chrome at least, it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.

However, there is a simple way to avoid this in your code:

var s = ["hi"];
console.log(s.toString());
s[0] = "bye";
console.log(s.toString());

By calling toString, you create a representation in memory that will not be altered by following statements, which the console will read when it is ready. The console output is slightly different from passing the object directly, but it seems acceptable:

hi
bye

Weird behavior with objects & console.log

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));


Related Topics



Leave a reply



Submit