Archive for the ‘Firebug’ Category

Javascript: Function.prototype.toString returns an optimized version of the function

June 17, 2007

I was working an a user script for Gmail (I’ll link to it when it’s done), and could not understand why some code didn’t run on a specific page.

One of my tricks of seeing a Javascript function body when the function is dynamically added is to call the function toString() (e.g. in Firebug console). Regretfully, Firebug doesn’t tab-complete functions’ methods, so I have to manually type “toString()”. (I opened issue 959 for this.)

However, in the code I wrote, I accidentally wrote something like:

var count = getCount();
if(count == 0)
    count == 1;

Note the bug in the last line, where the comparison operator (==) is used instead of the assignment operator (=). Surely, my mistake. However, when I look at the text that was returned from the call to Function.prototype.toString() for that function, I saw it is:

var count = getCount();
if (count == 0) {
}

So the Javascript engine noticed that nothing really useful is going on in the body of that if, and simply removed it, and that is reflected in what Function.prototype.toString returns. I didn’t knew that.

PS

Naturally tools like JSLint warn about this problem:

Expected an assignment or function call and instead saw an expression.

count == 1;

But this is a minor user script, and I never considered passing such scripts through JSLint. I might consider starting doing it for my scripts…