Monitoring javascript functions

Debugging javascript can be hard… really hard.

There are times when you find yourself adding in a million console.log() calls (not alerts, no more javascript alerts!) just to try and figure out where on earth the interpreter is going.  There have been times where I’ve added one at the top of every function to try and figure out when they’re being called, especially for event handlers.

But there is a better way – monitor().

In the console you simply call monitor() passing in the function that you’re interested in, and then the next time that the function is called you get a message in the console like this…

function test called with arguments: Hello world

You can see an example of this below…

The first line is me creating the test function…

var test = function(say) { console.log('"'+say+'", she said'); };

The second line is me calling the function to show that it works…

test("Hello world")
//"Hello world", she said

The third line is me setting up the monitor…

monitor(test)

And the fourth line is me testing again to show the monitor working…

test("Hello world")
//function test called with arguments: Hello world
//"Hello world", she said

I don’t know how long this has existed, but I wish I’d known about it sooner.