RATCHET

RATCHET Labs

11/18/2010

The RIGHT way to debug Javascript

So, you spent 10 development hours writing the next-generation Javascript framework for your company. You’ve got the cold beer ready, the phone nearby to grab your buddies for a night on the town, and all but one of your test-cases have been executed flawlessly. You set up your last test case, load everything up, turn to leave. . . but your Javascript masterpiece sits there, doing nothing. Or throwing errors. Or actively cursing your ineptitude. What to do?

First, make sure you have a decent debugger. Firefox uses Firebug First, install it. Chrome and Safari use Webkit Inspector. Opera uses Dragonfly. IE8 and IE9 have a built-in debugger (F12). IE6 and IE7 require you to use a host app to debug. Dumb.

When you have a decent debugger, you can Debug the Right Way!

I can’t take credit for what you find below. People smarter and older than me have passed these tricks down. I CAN, however, sing the praises of the following methods.

1. Alerts aren’t debugging tools. Stop Using Them As Such. Seriously. Now. “But Adam, I’ve always done this and it works. I find the problem!” My answer is “So?” People used to poop in the streets all the time, and that worked too. But then something better was invented as a way to dispose of feces. Alerts are the equivalent of an uncivilized man defecating in Times Square. Time to join (Javascript) civilization, folks.

2. Debuggers let you step through your code. Yes, like a full-fledged back-end developer debugging an application, you too can now watch the birth of the information from the framework you create. Learn about break-points. Learn to love them. Set them in your debugger. Set them manually ( debugger; ). But use them to debug your code. With a Debugger you can:

    a. Determine the current value of variables.

    b. Drill-down through objects – no more [Object object]!

    c. Watch: Keep track of arbitrary expressions

3. Learn the console() API. I won’t list everything, go to the firebug wiki to learn about it. Quick tip about the console() API – don’t just log properties. If you log the entire object, you can hover over the elements, if any, to see them highlighted in the page.

I highly recommend this slide show to anyone who works with Javascript, n00b or journeyman, to examine debugging. This specifically deals with jQuery, but is relevant to any library or Javascript framework. FixingTheseJquery.com.

  • Facebook
  • Twitter
  • Digg
  • Print
  • email