When used effectively,
JavaScript debuggers help find and squash errors in your JavaScript
code. To become an advanced JavaScript debugger, you'll need to know
about the debuggers available to you, the typical JavaScript debugging
workflow, and code requirements for effective debugging. In this
article, we'll discuss advanced debugging techniques for diagnosing and
treating bugs using a sample web application.
Debugging Workflow
When investigating a specific problem, you will usually follow this process:
- Find the relevant code in the debugger's code view pane.
- Set breakpoint(s) where you think interesting things may occur.
- Run the script again by reloading the page in the browser if it's
an inline script, or by clicking a button if it's an event handler.
- Wait until the debugger pauses execution and makes it possible to step through the code.
- Investigate the values of variables. For example, look for
variables that are undefined when they should contain a value, or
return "false" when you expect them to return "true."
- If necessary, use the command line to evaluate code or change variables for testing.
- Find the problem by learning which piece of code or input caused the error conditions.
To create a breakpoint, you can also add the statement
to your code:
1 | function frmSubmit(event){ |
3 | event = event || window.event; |
Considering how much time we all spend debugging, it is ironic how
rare a topic it is in books and conversation. So how does one become a
better debugger? Hopefully, the twelve guidelines I've compiled here
will help you squash bugs faster, smarter, and with more authority.
1. Organize Your Code
Let's face it, building websites isn't rocket science. If you've
been at it for 6 months, you've probably developed some sort of
methodology. All sites share common elements, pay attention to what
they are and re-use code as much as possible. Organize your code and
includes so you know where everything is.
The W3C is pushing standards that separate content from structure;
you'll find adopting this philosophy helps when debugging as well. Some
general guidelines:
Code Once, Include Often.
I'll say it again, organize your code so you know where everything is. Strive to have no duplicated code on your site.
Externalize Client-Side Scripts.
Put all CSS and JavaScript into external includes. Your pages will
load faster, as the scripts will go into the browser's cache. Also,
you'll be able to disable all your JavaScript or all your CSS more
easily. Resist the temptation from the darkside, never code CSS inline
or write javascripts willy-nilly through your pages. You'll be happy
later when you want to either turn it all off, or export it to another
project.
Refine It.
Every website gains features through the development cycle. When a
complex project reaches the 75% complete zone, it is usually begging,
pleading, and bleeding for a rewrite. Try to take the 2, 3, maybe 4
days it will take to go back through your code and refine it when it
feels out of hand. Don't be the type of a developer that has an FUNW
folder for an inbox. Try to build in as much scalability as you can
from the start.
2. Isolate and Identify the Problem
This is the key to all debugging, and a close cousin of code
organization. The problem code block must be identified, and identified
quickly. If you're debugging-while-developing (DWD), you know the first
place to look is the code you were just working on. If you're
debugging-while-updating, or wading through someone else's work,
isolation becomes more difficult.
Trust No-One.
Your first suspect should be the machine you're testing on. Is the
error totally bizarre? Does another, known to be working page serve OK?
Computers crash all the time, and test boxes that kick more errors than
successes all day will tend to crash more. If you test on a *nix box,
you probably find this paragraph funny. If you're on Windows, reboot
your test machine at least once a day.
Believe the Error Message.
If you're reasonably sure your machine is stable, look for clues in
the error message. It's funny how those messages make sense afterwards,
isn't it? Line numbers in error messages are almost always wrong, but
are invariably the best place to start looking. Head backwards from the
line number reported, and check the nesting of that segment. When you
can't find the error, comment out sections of your code until the error
stops popping. Then cut and paste the problem block into a separate
template for surgery.
3. Validate It
Make the validator your home
page. Writing valid HTML of some flavor is an excellent first step in
error prevention. If you're new to validation, start with 4.01
Transitional. There are also many standalone tools available, the W3C maintains a list here.
4. View the Source, Luke
When you're working server-side, many times you can find problems
faster by viewing what came out, rather than looking at what went in.
Check the output, test variables using HTML comment blocks, or use a
simple JavaScript alert to dump server-side variables. If you're
dealing with a variable that changes throughout the page, output it
several times.
5. Man-Handle Forms
Everyone hates forms. If you don't, you haven't done enough
multi-page checkouts yet. Bulletin boards everywhere are crawling with
people having form trouble, and it's almost always related to bad-HTML
or a misnamed field.
Dissect the Form Elements.
Break down the form into small chunks until you find the problem. If
you're using the POST method, does the page even submit? How about with
one variable? Same for the GET method, can you pass at least one
variable and have it show in the URL of the target page?
Name Fields Sensibly.
If the form fields correspond to table columns in a database, use
the same names for both, or adhere to some naming convention. Always
build and debug server-side validation before introducing any
JavaScript validation.
6. Mirror Your Test and Production Setups.
If you've ever uploaded files to the server with a local path
unchanged, take off your left shoe and eat it. The feeling is right up
there with sitting in the Principal's office, or locking your keys in
your car.
Mirror the Server Setup.
Though not always possible, the advantages of having the same
physical drive and folder setup as your production box are huge, and
can save you hours of heartache and sweat drenched ftp sessions.
Use Absolute Paths.
Consider using absolute paths as much as possible. Avoid using the
<base ... > tag, as it will inevitably lead to disaster. A long long
long time ago, I uploaded a site with a <base ... > tag set to
127.0.0.1. Can you guess what happened? Everything seemed fine when I
tested the uploads, because the live site was referencing my local
machine. Whatever you do, don't mix absolute and relative paths-choose
one and avoid the other.
Debugging Tools
Firebug Lite -
works in IE and other browsers, and if you're using the Dojo Toolkit it
comes included, with some enhancements like launching in a separate
window, and an object inspector. And of course there's itself, but you knew that.
Debug Bar - Debug Bar Core Services has released ,
a Firebug equivalent for IE. Great inspectors for the DOM, HTTP, script
and style sheets. Plus it provides you with much needed IE error
handling. It has a JS command line, but in spite of its claims, it
seems to be lacking any actual logging.
Fiddler
is a very robust proxy that logs your HTTP calls. More information than
you'll ever need. Claims to work all browsers, but it uses the .NET
Framework, so it's Windows only.
HTTP Live Headers - works on a Mac, and captures all of your HTTP calls.
Web Development Helper - Another Firebug equivalent for IE,
is a pretty nice little app, with many of the same features as Debug
Bar, except that it's free, and it actually has a logging feature,
although it's plain text. A lot of the information appears in pop-up
windows, which hurts persistence. It has an object inspector, but that
too is in a window. However, this is definitely worth a look.
Internet Explorer Developer Toolbar - Microsoft's is
certainly an improvement over what it had before. A lot of inspectors
and shortcuts to useful features like cache clearing (which now takes
two clicks instead four).
(Img Credit to artfuldodger)
|