Loops and Debugging In JavaScript

In This Chapter

Creating for loops Learning for loop variations Building flexible while loops Making well-behaved while loops Recognizing troublesome loops Catching crashes with debugging tools Catching logic errors Using the Aptana line-by-line debugger Using the Firebug debugger Watching variables and conditions
Computer programs can do repetitive tasks easily. This is accomplished ^^through a series of constructs called loops. A loop is a structure that allows you to repeat a chunk of code. In this chapter you learn the two major techniques for managing loops.
Loops are powerful, but they can be dangerous. It’s possible to create loops that act improperly, and these problems are very difficult to diagnose. But don’t worry. I demonstrate a number of very powerful techniques for looking through your code to find out what’s going on.

Building Counting Loops with for

One very standard type of loop is the for loop. You use these loops when you want to repeat code a certain number of times. Figure 4-1 shows a for loop in action:
It looks like ten different alert() statements, but there’s only one. It just got repeated ten times.
This loop repeats ten times before it stops.
Figure 4-1:
This loop repeats ten times before it stops.
In Figure 4-1, and some of the other looping demos in this chapter, I show the first few dialog boxes and the last. You should be able to get the idea. Be sure to look at the actual program on either of the companion to see how it really works.


Building a standard for loop

The structure of the for loop can be seen by studying the code:
tmp7B44_thumb_thumb
for loops are based on an integer (sometimes called a sentry variable). In this example, lap is serving as the sentry variable. The sentry variable is normally used to count the number of repetitions through the loop.

The for statement has three distinct parts:

Initialization: This segment (lap = 1) sets up the initial value of the sentry.
Condition: The condition (lap <= 10) is an ordinary condition (although it doesn’t require parentheses in this context). As long as the condition is evaluated as true, the loop will repeat.
Modification: The last part of the for structure (lap++) indicates the sentry will be modified in some way throughout the loop. In this case, I add one to the lap variable each time through the loop.
The for structure has a pair of braces containing the code that will be repeated. As usual, all code inside this structure is indented. You can have as much code inside a loop as you want.
The lap++ operator is a special shortcut. It’s very common to add one to a variable, so the lap++ operation means “add one to lap.” You could also write lap = lap + 1, but lap++ sounds so much cooler.
When programmers decided to improve on the C language, they called the new language C++. Get it? It’s one better than C! Those computer scientists are such a wacky bunch!
for loops are pretty useful when you know how many times something should happen.

Making a backwards loop

You can modify the basic for loop so it counts backward. Figure 4-2 shows an example of this behavior.
This program counts backward by using a for loop.
Figure 4-2:
This program counts backward by using a for loop.
The backward version of the for loop uses the same general structure as the forward version, but with slightly different parameters:
tmp7B46_thumb_thumb
If you want to count backward, just modify the three parts of the for statement:
Initialize the sentry to a large number: If you’re counting down, you need to start with a larger number than 0 or 1.
Keep going as long as the sentry is larger than some value: The code inside the loop will execute as long as the condition is true. The number will continue to get smaller, so make sure you’re doing a “greater than” or “greater than or equal to” comparison.
Decrement the sentry: If you want the number to get smaller, you need to subtract something from it. The — operator is a quick way to do this. It subtracts 1 from the variable.

Counting five at a time

You can use the for loop to make other kinds of counting loops. If you want to count by fives, for example, you can use the following variation:
tmp7B47_thumb_thumb
This code starts i as 5, repeats as long as i is less than or equal to 25, and adds 5 to i on each pass through the loop. Figure 4-3 illustrates this code in action.
If you want a for loop to skip numbers, you just make a few changes to the general pattern.
Initialize the sentry to 5: I want the loop to start at 5, so that’s the initial value.
Compare the sentry to 25: It makes sense for a 5 loop to end at a multiple of 5. I want this loop to continue until we get to 25, so the loop will continue as long as i is less than or equal to 25.
Add 5 to i on each pass: The statement i += 5 adds 5 to i. (It’s just like saying i = i + 5 .)
A for loop can also skip values.
Figure 4-3:
A for loop can also skip values.
The key to building for loops is to remember these three elements and make sure they work together: Build a sentry variable, give it a sensible initial value, check against a condition, and modify the variable on each pass.
This is easy to do in a for loop, because all these elements are in the for loop structure. Still, if you find your loop isn’t working as expected, you might need to look into the debugging tricks described later in this chapter.

Looping for a while

The for loop is useful, but it has a cousin that’s even more handy, called the while loop. A while loop isn’t committed to any particular number of repetitions. It simply repeats as long as its condition is true.

Creating a basic while loop

The basic while loop is deceptively simple to build. Here’s an example:
tmp7B49_thumb_thumbtmp7B50_thumb_thumb
This script asks the user a simple math question — and keeps asking until the user responds correctly. You can see it in action in Figure 4-4.
This loop continues until the user enters the correct answer.
Figure 4-4:
This loop continues until the user enters the correct answer.
The operation of a while loop is pretty easy to understand. Here’s how the math program works:
1. Create a variable called answer.
This will act as a sentry variable for the loop.
2. Initialize the variable.
The initial value of the variable is set to “-99″, which can’t possibly be correct. Doing so guarantees that the loop will execute at least one time.
3. Evaluate what’s in the answer variable.
In this particular program the correct answer is 5. If the value of answer is anything but 5, the loop continues. I’ve preset the value of answer to “-99″, so you know it’s going to happen at least once.
4. Ask the user a challenging math question.
Well, a math question anyway. The important thing is to change the value of answer so it’s possible to get 5 in answer and then exit the loop.
5. Give the user some feedback.
It’s probably good to let the user know how she did, so provide some sort of feedback.

Avoiding loop mistakes

A while loop seems simpler than a for loop, but while has exactly the same basic requirements:
There is usually a critical sentry variable. while loops are usually (but not always) controlled by some key variable.
The sentry must be initialized. If the loop is going to behave properly, the sentry variable must still be initialized properly. In most cases, you’ll want to guarantee that the loop happens at least one time.
You must have a condition. Like the for loop, the while loop is based on conditions. As long as the condition is true, the loop continues.
There must be a mechanism for changing the sentry. Somewhere in the loop you need to have a line that changes the value of the sentry. Be sure that it’s possible to make the condition logically false, or you’ll be in the loop forever!
If you forget one of these steps, the while loop might not work correctly. It’s easy to make mistakes with your while loops. Unfortunately, these mistakes don’t usually result in a crash. Instead, the loop might either refuse to run altogether or continue indefinitely.

Introducing Some Bad Loops

Sometimes loops don’t behave. Even if you’ve got the syntax correct, it’s possible that your loop just doesn’t do what you want. Two main kinds of loop errors are common: loops that never happen, and loops that never quit.

Managing the reluctant loop

You might write some code and find that the loop never seems to run. Here’s some of a program that illustrates this woeful condition:
tmp7B52_thumb_thumb
This code looks innocent enough, but if you run it, you’ll be mystified. It doesn’t crash, but it also doesn’t seem to do anything. If you follow the code step by step, you’ll eventually see why. I initialize i to 1, and then repeat as long as i is greater than 10. See the problem? i is less than 10 at the very beginning, so the condition starts out false, and the loop never executes! I probably meant for the condition to be (i < 10). It’s a sloppy mistake, but exactly the kind of bone-headed error I make all the time.

Managing the compulsive loop

The other kind of bad-natured loop is the opposite of the reluctant loop. This one starts up just fine, but never goes away!

The following code illustrates an endless loop:

tmp7B53_thumb_thumb
If you decide to run endless.html, be aware that it will not work properly. What’s worse, the only way to stop it will be to kill your browser through the Task Manager program. I show you later in this chapter how to run such code in a “safe” environment so you can figure out what’s wrong with it.
This code is just one example of the dreaded endless loop. Such a loop usually has perfectly valid syntax, but a logic error prevents it from running properly. The logical error is usually one of the following:
The variable was not initialized properly. The initial value of the sentry is preventing the loop from beginning correctly.
The condition is checking for something that cannot happen. Either the condition has a mistake in it, or something else is preventing it from triggering.
The sentry has not been updated inside the loop. If you simply forget to modify the sentry variable, you’ll get an endless loop. If you modify the variable, but do it after the loop has completed, you get an endless loop. If you ask for input in the wrong format, you might also get a difficult-to-diagnose endless loop.

Debugging Your Code

If you’ve been writing JavaScript code, you’ve also been encountering errors. It’s part of a programmer’s life. Loops are especially troublesome, because they can cause problems even if there are no syntax errors. Fortunately, there are some really great tricks you can use to help track down pesky bugs.

Letting Aptana help

If you’re writing your code with Aptana, you already have some great help available. It gives you the same syntax-highlighting and code-completion features as you had when writing XHTML and CSS.
Also, Aptana can often spot JavaScript errors on the fly. Figure 4-5 shows a program with a deliberate error.
Aptana caught my error and provides some help.
Figure 4-5:
Aptana caught my error and provides some help.
Aptana notifies you of errors in your code with a few mechanisms:
The suspect code has a red squiggle underneath. It’s just like what a word-processing spell-checker shows you for a suspect word.
A red circle indicates the troublesome line. You can scan the margin and quickly see where the errors are.
All errors are summarized in the validation pane. You can see the
errors and the line number for each. Double-click an error to be taken to that spot in the code.
You can hover over an error to get more help. Hover the mouse pointer over an error to get a summary of the error.
Aptana can catch some errors, but it’s most useful for preventing errors with its automatic indentation and code-assist features. The browsers are where you’ll usually discover logic and errors. Some browsers are more helpful than others when it comes to finding and fixing problems.

Debugging JavaScript on IE

Microsoft Internet Explorer has unpredictable behavior when it comes to JavaScript errors. IE6 will take you to some type of editor, but the editors have changed over the years, and are modified (without your knowledge or permission) when you installed new software. IE7 and IE8 (at least by default) simply do nothing. You won’t see an error, or any indication there was an error. (Denial — my favorite coping mechanism.)

Here’s how you can force IE to give you a little bit of help:

1. Choose Tools Internet Options Advanced.
You’ll see a dialog box that looks like Figure 4-6.
The Internet Options dialog box allows you to get error warnings in Internet Explorer.
Figure 4-6:
The Internet Options dialog box allows you to get error warnings in Internet Explorer.
2. Choose “Display a Notification about Every Script Error.”
Leave all the other settings alone for now. Yep, we’re going to keep script debugging disabled, because it doesn’t work very well. I’ll show you a better technique later in this chapter (see the “Using the Firebug Debugger” section).
Now, when you reload broken.html in IE, you’ll see something like Figure 4-7.
I never thought I'd be happy to see an error message.
Figure 4-7:
I never thought I’d be happy to see an error message.
This is actually good news, because at least you know there’s a problem, and you’ve got some kind of clue how to fix it. In this particular case, the error message is pretty useful. Sometimes that’s the case, and sometimes the error messages seem to have been written by aliens.
Be sure to have the error notification turned on in IE so you know about errors right away. Of course, you’ll also need to check your code in Firefox, which has tons of great tools for checking out your code.

Finding errors in Firefox

Firefox has somewhat better error-handling than IE by default, and you can use add-ons to turn it into a debugging animal. At its default setting, error notification is minimal. If you suspect JavaScript errors, open up the JavaScript Errors window. You can do this by choosing Error Console from the Tools menu, or by typing javascript: in the location bar. Figure 4-8 shows the error console after running broken.html.
I generally find the error messages in the Firefox console more helpful than the ones provided by IE.
The Error console doesn’t automatically clear itself when you load a new page. When you open it up, there might be a bunch of old error messages in there. Be sure to clear the history (with the Error Console’s Clear button) and refresh your page to see exactly what errors are happening on this page.

Catching syntax errors with Firebug

One of the best things about Firefox is the add-on architecture. Some really clever people have created very useful add-ons that add wonderful functionality. Firebug is one example. This add-on (available at https://addons. mozilla.org/en-US/firefox/addon/1843) tremendously expands your editing bag of tricks.
The Firefox Error Console is pretty useful.
Figure 4-8:
The Firefox Error Console is pretty useful.
Firebug (first introduced in Chapter 1) is useful for HTML and CSS editing, but it really comes into its own when you’re trying to debug JavaScript code.
When Firebug is active, it displays a little icon at the bottom of the browser window. If there are any JavaScript errors, a red error icon will appear. Click this icon, and the Firebug window appears, describing the problem. Figure 4-9 shows how it works.
The Firebug tool shows an error. Click the error line to see it in context.
Figure 4-9:
The Firebug tool shows an error. Click the error line to see it in context.
If you click the offending code snippet, you can see it in context. This can be useful, because the error might not be on the indicated line. Generally, if I’m doing any tricky JavaScript, I’ll have Firebug turned on to catch any problems.
The Firebug Lite version of Firebug can be used in other browsers (IE, Chrome, and Safari). This version is accessed as a bookmarklet, meaning you can put a link to the code in your bookmarks and use this program to get most of the features of Firebug in these other browsers. Check http://getfirebug. com/lite.html for details.

Catching Logic Errors

The dramatic kind of error you see in broken.html is actually pretty easy to fix. It crashes the browser at a particular part of the code, so you get a good idea what went wrong. Crashes usually result in error messages, which generally give some kind of clue about what went wrong. Most of the time, it’s a problem with syntax. You spelled something wrong, forgot some punctuation, or something else pretty easy to fix once you know what’s wrong.
Loops and branches often cause a more sinister kind of problem, called a logical error (as opposed to a syntax error). Logical errors happen when your code doesn’t have any syntax problems, but it’s still not doing what you want. These errors can be much harder to pin down, because you don’t get as much information.
Of course, if you have the right tools, you can eventually track down even the trickiest bugs. The secret is to see exactly what’s going on inside your variables — stuff the user usually doesn’t see.

Logging to the console with Firebug

Firebug has another nifty trick: You can send quick messages to the Firebug console. Take a look at log.html:
tmpB23_thumb_thumbtmpB24_thumb_thumb
This code is special, because it contains several references to the console object. This object is only available to Firefox browsers with the Firebug extension installed. When you run the program with Firebug and look at the Console tab, you’ll see something like Figure 4-10.
The console object allows you to write special messages that will only be seen by the programmer in the console. This is a great way to test your code and see what’s going on, especially if things aren’t working the way you want.
If you want to test your code in IE, there’s a version of Firebug (called Firebug Lite) that works on other browsers. Check the Firebug main page to download and install this tool if you want to use console commands on these browsers. Note that the syntax for using the console might be a bit different when you’re using Firebug Lite. Check the main site for details.
The Firebug console shows lots of new information.
Figure 4-10:
The Firebug console shows lots of new information.

Looking at console output

Here’s how it works:

‘ The first loop prints the value of i to the console. Each time through the first loop, the console.log function prints out the current value of i . This would be very useful information if (for example) the loop wasn’t working correctly. You can use the console.log() method to print the value of any variable.
The second loop demonstrates a more elaborate kind of printing.
Sometimes you’ll want to make clear exactly what value you’re sending to the console. Firebug supports a special syntax called formatted printing to simplify this process.
console.log(“i is now %d.”, i);
The text string “i is now %d” indicates what you want written in the console. The special character %d specifies that you will be placing a numeric variable in this position. After the comma, you can indicate the variable you want inserted into the text.
There are other formatting characters you can use as well. %s is for string, and %o is for object. If you’re familiar with printf in C, you’ll find this technique familiar.
You can specify more urgent kinds of logging. If you want, you can use alternatives to the console.log if you want to impart more urgency in your messages. If you compare the code in log.html with the output of Figure 4-10 you’ll see how info, warning, and error messages are formatted.
When your program isn’t working properly, try using console commands to describe exactly what’s going on with each of your variables. This will often help you see problems and correct them.
When you get your program working properly, don’t forget to take the console commands out! Either remove them or render them ineffective with comment characters. The console commands will cause an error in any browser that does not have Firebug installed. Typically, your users will not have this extension (nor should they need it! You’ve debugged everything for them!).

Using an Interactive Debugger

Traditional programming languages often feature a special debugging tool for fixing especially troubling problems. A typical debugger has these features:
The capability to pause a program as it’s running: Logic errors are hard to catch because the program keeps on going. With a debugger, you can set a particular line as a breakpoint. When the debugger encounters the breakpoint, the program is in a “pause” mode. It isn’t completely running, and it isn’t completely stopped.
A mechanism for moving through the code a line at a time: You can normally step through code one line at a time checking to see what’s going on.
A way to view the values of all variables and expressions: It’s usually important to know what’s happening in your variables. (For example, is a particular variable changing when you think it should?) A debugger should let you look at the values of all its variables.
The capability to stop runaway processes: As soon as you start creating loops, you’ll find yourself accidentally creating endless loops. In a typical browser, the only way out of an endless loop is to kill the browser with the task manager (or process manager in some operating systems). That’s a bit drastic. A debugger can let you stop a runaway loop without having to access the task manager.
Debuggers are extremely handy, and they’ve been very common in most programming languages. JavaScript programmers haven’t had much access to debugging tools in the past, because the technical considerations of an embedded language made this difficult.
Fortunately, Firebug and Aptana both have interactive debuggers that provide all these features. Even better, they work together to provide you lots of useful help.
Aptana has a debugger built in. Originally, this involved a special Firefox plugin that sent information back to Aptana. The developers of Firebug and Aptana are now working together to give Firebug the ability to work directly with Aptana. When you use the Aptana debugger, it works automatically with Firebug.
To test the debuggers, I wrote a program with a deliberate error that would be hard to find without a debugger:
tmpB26_thumb_thumb
This is another version of the endless.html program from earlier in this chapter. You might be able to see the problem right away. If not, stay tuned; you’ll see it as you run the debugger. Even if you can tell what’s wrong, follow along so you can learn how to use the debugger when you need it.
I used console.log() for output in this program just to avoid jumping back and forth from the browser to the editor to handle dialog boxes.
To step through a program using the Aptana debugger, begin by loading the file into the debugger.

Adding a breakpoint

So far your JavaScript programs have been pretty small, but they’re going to get much larger. You usually won’t want to start the line-by-line debugging from the beginning, so you need to specify a breakpoint. When you run a program in Debug mode, it runs at normal speed until it reaches a breakpoint — and then it pauses so you can control it more immediately.
To set a breakpoint, right-click a line number in the code editor.
Figure 4-11 shows me setting a breakpoint on line 12 of the debug.html code.

Running the debugger

The debugger requires you to run your program in a different way than you might be used to. Since your program is normally run by the browser (not Aptana), somehow you need a mechanism for passing information back from the browser to Aptana.
1. Start the debugger by clicking the Debug icon. It looks like a little bug.
2. Install the Aptana Firefox plugin automatically.
When you debug a JavaScript program for the first time, Aptana asks permission to install an additional Firefox plugin. Click Yes to complete the installation. You will only need to do this once.
3. Switch to the Debug perspective.
Aptana pops up a message box to ask whether you want to switch to the Debug perspective. Answer Yes to change Aptana (temporarily) to Debug configuration.
Use a breakpoint to tell the debugger where to pause.
Figure 4-11:
Use a breakpoint to tell the debugger where to pause.

Using the Debug perspective

When Aptana is used for debugging, it introduces a new layout (called a perspective in Aptana). This changes the way the screen looks, and optimizes the editor for debugging mode. Figure 4-12 shows the debug.html program in Debug perspective.

The Debug perspective changes the editor to emphasize debugging:

The code completion window is gone. This feature isn’t needed when you’re debugging, so it’s removed. You need the screen space for other goodies.
The file management window is also missing. Likewise, you won’t be doing a lot of file manipulation in Debug mode, so this window is gone too. (Don’t worry; you’ll get it back when you return to normal edit mode.)
Aptana looks a little different in Debug perspective.
Figure 4-12:
Aptana looks a little different in Debug perspective.
You have a new debug window. This window shows your active threads. The most important thing about it is the buttons along the top.
You also have a window showing breakpoints and variables. This powerful new window describes the values of all your variables while the program is running.
Most of the other windows are the same. You still have the code window, console, and outline window, but they are rearranged a little differently than normal. Of course you can adjust them if you wish.
Once you’ve got the debug mode running one time, you’ll have a little Debug icon in the upper right of the Aptana interface. When this quick button is available, you can use it to switch into Debug mode. Use the Aptana button to move back to ordinary editing mode.

Examining Debug mode with a paused program

When you run your code through the debugger, Aptana fires up a new instance of Firefox, and loads your program into it. When your program is paused for debugging, you’ll see a few new details, shown in Figure 4-13.
When your program is paused, you can see several important new indicators:
The Debug window shows which script is active. Right now your programs have only one script, but later you’ll have more. The thread window tells you which script currently has the processor’s attention.
The buttons in the Debug window are active. Mouse over each of the new buttons to see their tooltips. I explain these buttons in the upcoming section on stepping through your code.
You get a few new buttons and tools when you're debugging a program.
Figure 4-13:
You get a few new buttons and tools when you’re debugging a program.
The Breakpoints panel has more panes. In addition to the breakpoints and variables panes, you’ll see some new panes, expressions, and scripts.
The Variables panel lets you see all the variables the page knows about. Even though this program contains only two explicitly defined variables, there seems to be a lot more than that. Every JavaScript program has a whole bunch of special variables built in. (I explain how to use this panel later in this chapter.)
The Breakpoints panel allows you to manage your breakpoints. This is a good place for you to see all of the breakpoints in your project. You can enable or disable a breakpoint from this panel.
The Expressions panel allows you to follow particular variables or expressions. It’s an extremely powerful tool. I demonstrate its use later in this chapter.
The current line of code is highlighted. If you set a breakpoint on line 12, you’ll see that line highlighted. (It might be difficult to see in Figure 4-13.) As you move through the code, you’ll see this highlight move. This will help you to follow the logic.
In some versions of Aptana, a message that starts Type Error: request. load Group has no properties appears sometimes when you are debugging a program. This is not an error in your code, and it doesn’t seem to cause any problems. You can safely ignore this error. I’ve also run across a “socket connection” error once in a while. Normally you can restart Firefox to fix this problem.

Walking through your program

Here’s the best part. You can run your program in super slow-mo, seeing every aspect of its behavior.
1. Take a step.
Click on the Step Into button on the Debug panel. (It looks like a curved arrow pointing between two dots, or just use the F5 key.)
2. Look at the code.
The highlighting has moved to the next line (line 13).
3. Mouse over the variables.
Hover your mouse pointer over the two variables (i and j) in your code. You’ll see a dialog box that describes the current value of each variable.
4. Take a few more steps.
Use the Step Into button a few more times. Watch as the highlight moves through the program, looping.
5. Check the variables again.
Take another look at the variables after a few times through the loop, and you’ll begin to see what’s wrong with this code: j is increasing, but i is still stuck at 0.
6. Stop the debug session.
If you think you understand the problem, you can stop the debug session with the red square Terminate button. (You’ll need to do that in this program, because it’s an endless loop. It will never end on its own.) Aptana will close down the generated Firefox instance.
If the debugger isn’t acting properly, be sure you’ve set a breakpoint. If you don’t have a breakpoint, the program won’t stop. Also, be sure you’ve used the Debug button to start the program. Using the Run program or viewing the page directly in the browser won’t activate the debugger.

Viewing expression data

The whole point of debugging is to find difficult problems. Usually, these problems are variables that aren’t doing what you expect. Aptana provides a Variables tab, which shows the value of all variables in a program, but it’s surprisingly difficult to use. JavaScript programs come bundled with hundreds of variables. If you dig around, you can eventually find the i and j variables. (Scroll down in the variables panel to find them.) Every time you take another step, you have to scroll down again to see the values, or mouse over the variables in the code.
Fortunately, Aptana provides a much easier way. Select a variable with the mouse and right-click. In the resulting menu, choose Watch. Figure 4-14 shows the debugger after I’ve chosen to watch both variables and run through the loop a few times.
In this mode, you can see the exact values of the variables you’ve chosen to track. When the variable changes value, you can see it happen immediately.
The Expression window has one more cool trick: You can use it to watch complex expressions, not just variables. In this program, you want to know why the loop isn’t exiting. Highlight the condition (i <= 10) and add it to the watch expressions just as you did the variables.
Now step through the program watching the variables and the condition. With all this information available to you, my coding mistake becomes obvious: I used the variable i in the condition, but I never changed it inside the loop. Instead, I changed the value of j, which has nothing at all to do with the loop!
The expressions window highlights the variables I'm interested in.
Figure 4-14:
The expressions window highlights the variables I’m interested in.
Whenever you encounter a program that isn’t doing what you want, fire up the debugger, watch the critical values, and step through the code a line at a time. This will often help you find even the most difficult errors.

Using the Firebug debugger

The Aptana debugger is very good, but I’ve found it to be a bit cranky. It complains if the version of Firebug isn’t exactly right, and sometimes it gives you trouble with other extensions. Fortunately, Firebug has a debugger that’s just as good as Aptana (except for one notable limitation). Figure 4-15 shows the Firebug debugger in action.
The Firebug debugger is very similar to the one in Aptana.
Figure 4-15:
The Firebug debugger is very similar to the one in Aptana.
Firebug’s debugger works in the same general way as the Aptana debugger. Here’s how to use it:
1. Open up the suspect file in Firefox.
Of course, you’ll need to load up the file before you do so.
2. Open the Firebug <script> tag.
You might need to enable scripts for local files.
3. Set a breakpoint.
Click the line number where you want the breakpoint to go. A red dot will appear, indicating the breakpoint.
4. Reload the page.
Use the F5 key or reload button to reload the page in debug mode.
5. Watch the page pause at the breakpoint.
As with the Aptana debugger, you’re placed in a pause mode with the program resting at the breakpoint.
6. Use the Step Into and Step Over buttons to move through the code.
The Firebug debugger has the same Step Into and Step Over buttons as the Aptana debugger. Use them to walk through your code one line at a time.
7. Type in a variable name or condition in the watch expression menu.
This allows you to track any particular variables or conditions that are giving you trouble.
The Firebug debugger is very easy to use, but it has one significant flaw: It can only be used after a program has loaded into memory. If a program immediately goes into an endless loop (as endless.html in this chapter does), the program never stops executing and you never get access to the debug sessions.
Most JavaScript programs are written in a way that prevents this problem (look at Chapter 6 for information on how to pre-load JavaScript code). However, you might not be able to debug every program you encounter using the Firebug debugger.
Of course, you don’t necessarily need a debugger at all. JavaScript debuggers are relatively new, and people have been writing JavaScript without them for years. You can always do it the old-fashioned way: good old alert() statements. If you’re not sure what’s going on in your code, alert every variable to see its value. Of course, don’t forget to remove the alert() statements when you’re done.

Next post:

Previous post: