You are currently browsing the JD Smith: UI Developer blog archives for November, 2012

Debugging Tricky Javascript Problems Quickly

Often in web application development, developers run into bugs that are not causing a javascript error in the console. This usually happens when their code is simply not functioning to spec, but it can also happen when correct javascript is running so slowly that it “freezes” the application.

When faced with a tricky bug like this, I can get so detail-minded that I forget the broader goal: to find the bug as quickly as possible.

It seems obvious but I suspect I’m not alone as a programmer. I get a hunch as to what’s causing the problem, and I dive right in to that spot in the code. Sometimes I’m right, sometimes not.

Follow your hunch, but only for a minute.

Go ahead and try changing the code you think is causing the problem, if you have a reasonably good hunch. But don’t spend more than a minute or two on this. If it goes longer than that, you will save time on average by skipping to the next step:

Use the process of elimination

Start deleting portions of the code, and refreshing after each deletion, to identify which part of the code is causing the problem. Usually I’ll delete a few sections in succession so as to remove almost everything except the component that had the problem. This would show me whether the problem stems from some of the other code on the page, or a collision with that code.

If the problem still remains, that’s great – I’ve narrowed it down to just that component and can then dig into it in a similar fashion.

But if the problem disappeared after deleting the section(s) of code, then I know it’s somewhere in the code I deleted. I can just “undo” one section deletion at a time and refresh the page after each one, bringing back the code piecemeal until the problem appears.

Once the problem code is found, return to conventional debugging.

When I can no longer eliminate code and have found the problem spot, then I scan those lines to see if anything jumps out at me.

If I don’t see any obvious mistakes, I can go back to using the debug console to check that variable types and values are coming in properly, and step through in as much detail as is required to get to the bottom of it.

If you’ve never used the debug console much, this Firebug wiki page will get you going in no time.

Find slowness culprits using Chrome’s Profiler

Whenever a page has performance problems, the very first thing I do is run it through Chrome’s Javascript CPU Profiler. This shows me exactly how much time each function and method takes, making it much easier to locate problems. Here’s a screenshot of the profiler:

It can be more difficult to work with minified or obfuscated javascript in the profiler, so often times it’s sensible to use it on the un-minified versions of your scripts so you can see meaningful names.

I hope this helps you debug more efficiently!