Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Becoming a Better Web Developer: Debugging Javascript

When I first started "web development" I knew nothing more than a handful of tags, and that "Javascript is bad!".  As my HTML vocabulary grew, I started to see some of the really cool things you could do with DHTML, but most of it required that naughty Javascript.  Well, eventually I shook free from the unfounded notion that Javascript was bad, and have never looked back.  My goal here is to give you tips to help you become the skill full ninja you've always wanted to be.  We'll start out with some debugging tips working with Javascript, but I'm going to do this as a multi-part series which will also include working with css, and other points of interest for web developers.

Debugging is something that inevitably comes up, no matter what language you're using.  I remember my days of debugging when I was an undergrad, where we had an extremely sophisticated debugger - System.out.println (yes, most of my undergrad studies were done in Java).  If you're working in the Javascript world, you've likely found alert("it worked!"), which is the equivalent. 

It wasn't until my first real programming job, that I was introduced to an actual debugger, and it changed my world.  I went from having to write println statements all over my code to trace values and execution paths, to being able to literally step through each line of code and see what the entire stack looked like!  Woah!  So what does this have to do with becoming a better web developer?  Easy - if you're still using the alert("it worked") debugging style, it's time to graduate.

Debugging An Exception

Visual Studio 2005 and 2008 have excellent support for debugging Javascript in Internet Explorer.  But there are a couple of things you'll want to do.  The first step is to set IE to throw up Javascript errors, rather than swallowing them.  This is done through "tools -> options" of course.  Go to the Advanced Tab and uncheck the boxes for Disabling script debugging

image

Unchecking these boxes will open you up to a world you had happily ignored for years - the world of Javascript errors.  At this point, each time the browser encounters a Javascript error, it will pop up a message asking if you wish to debug.  You'd be amazed at the number of sites out there which throw up Javascript errors.. mostly the errors are produced by sites with embedded ads.  But anyway, back to the debugging exercise.  If you were trying to do something in Javascript and it didn't work, chances are it threw an error and execution was aborted.  By simply running the page now, you'll get that error notification, and you can begin debugging at the specific place in the code where the error was found. 

Let's take a look at an example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">
        function myFunction() {
            var a = document.getElementById("element");
            var b = a.style.backgroundColor;
        }
    </script>

</head>
<body>
    <button onclick="javascript:myFunction()">
        Click</button>
</body>
</html>

Run this page, and click on the button "Click"

image

Notice the error message that pops up, and the option to begin debugging.  Click on Yes.

image

Another dialog pops up which asks you to attach a debugger.  You can choose your existing application, or open a new instance of the Script Editor or Visual Studio 2008.  I usually go with the existing application, but from time to time I decide I want to debug in a new instance of Visual Studio 2008.  I generally don't use the Script Editor, unless I accidentally click on it.

After you choose which debugger to attach to, it will open or if already opened it will begin blinking in your taskbar.  Click on the debugger (Visual Studio) and you'll see another dialog window:

image

At this point, you want to click on "break".  If an error was thrown, clicking on continue will just cause the error to be thrown again, and prompt you to break or continue.  It reminds me of the old "Abort, Retry, OK" messages in DOS.. Abort was usually the only one that actually did anything.. so what was the purpose of the other options?  Anyway, after click on the break button, the debugger will be yours to play with.  At this point, you'll want to focus your attention on the document with the error highlighted, as well as the Watch window.  If your watch window isn't showing up, click on the Debug menu at the top of Visual Studio, Select the Windows item, and then the Watch item - finally click on one of the Watch Windows in the list. 

So what went wrong here?  Well let's take a look.  Hover over any part of the highlighted line, and you'll see the value as a tooltip. 

image

In our case, a is null.  Looking at the code, a is assigned as document.getElementById("element"), so my guess is that returned null, but how can we check for sure?  Go to the watch window, and paste that code in:

image

Notice it shows up as null?  Well, looking at the entire page, there's not a single element with the id "element", so I guess it's no surprise it returned null. But imagine if this was a more complex scenario where you had hundreds of elements on your page, and this was inside of a for loop which was being executed on a timer, etc.  Pretty cool right?  We can just zoom in on an error and see what's wrong!?  But it gets even cooler.   Lets go to our watch window and do a little exploring.  Type in "document".  Now you have a list of all properties of the "document" including all of the methods that can be called.  From this point on, the entire DOM is your playground.  And here's another trick..  you can set the line of code where the debugger is to execute by dragging the arrow as seen below.

image

Attach to Process

So we looked at debugging exceptions, where the browser launches the debugger for us, but what about when an exception isn't being thrown?  What about when the execution of your code just doesn't seem to be doing what it's supposed to be doing?  Well, you have 2 options here.  The first is to use the special keyword "debugger" in your Javascript.  Give it a try - throw that statement anywhere in your js file, and you'll get the debugger prompt when that statement is hit.  This is useful in a pinch, but there's a better way which doesn't require modifying your code - Attach To Instance.

If you've never never done it, it's time for you to try.  Go to the Debug menu in Visual Studio, and click Attach to Process.

image

At this point you should see the Attach to Process dialog, which give you a list of all current processes you can attach to.  If you want to debug javascript, you'll want to choose the iexplore.exe process with the Title that matches your page.  Note, you'll see a separate iexplore.exe process for each IE Window you have open, and the Title will correspond to the current tab in IE (so if you're in a mult-tab session, you may not see the title you were expecting).

image 

You can double click on the process which will immediately attach the debugger, or you can click once on the process and click the "Attach" button.  I prefer the double click..

Side-note: If you want to debug server-side code, rather than choosing the iexplore.exe process, you would choose the web server process.  If you're using IIS, you'll want aspnet_wp.exe, if you're using WebDevHelper (Cassini), you'll want to find WebDev.WebServer.EXE). 

Once the debugger is attached, you'll see the documents appear in the solution window in Visual Studio 2008, and the "Script Explorer" in Visual Studio 2005. 

image

Clicking on the document in question (error.aspx in this case) will open the 'running instance' of the document.  This is important because you can not set breakpoints in the original source document.  Well, actually you can, they just wont get hit.  So make sure all of your breakpoints are being set on the documents that show up under the "Script Documents" section.

The next time you reach into your toolbag and pull out an "alert", gently place it back and reach for Visual Studio instead - I promise you'll be pleased with your choice.  And if you need to debug in Firefox, download Firebug - a plugin for firefox.  It's a great debugger that embeds itself right into the browser. 

No Comments