Debugging Your JavaScripts

[ LiB ]

Debugging Your JavaScripts

In programming, there is one universal truth: Everyone makes mistakes. A mistake in a script is referred to as a bug . The process of finding and fixing bugs is called debugging and is a normal part of the development process. Even if you write a script that seems to work well right from the start, you still should perform a certain amount of testing and debugging to verify that the JavaScript works as expected in different scenarios.

In most cases, the browser will supply you with clues about where problems lie when you test your JavaScripts during script development. However, there will be times when things are not working correctly and the browser will not provide you with any error messages, leaving it totally up to you to locate and resolve the problem. Fortunately, there are a number of steps that you can follow to locate and fix bugs.

Debugging JavaScripts is neither glamorous nor fun, and it always seems to take longer than you anticipate. The bad news is that the longer your program is, the more errors you will see. The good news is that with time, experience, programming discipline, and a sound debugging process you will become proficient at debugging your scripts.

You are going to come across three types of errors when writing JavaScripts, as listed below. Each of these different types of errors is explained in detail in the sections that follow.

  • Load-time errors

  • Runtime errors

  • Logic errors

Load-Time Errors

Load-time errors occur when the browser attempts to load a HTML page that contains an HTML or script error. These errors tend to be fairly obvious and typically involve basic syntax issues. A syntax error occurs because the browser is unable to determine what the script is trying to do. Unlike human communications, a small syntactical error in computer code is enough to break down all communications. Remember that JavaScript is case sensitive and that you must be consistent in the manner in which you define and reference variables , functions, objects, methods , properties, and events.

Internet Explorer and Netscape Communicator used to display errors in pop-up dialog boxes that provided you with information about errors when they occurred. The current versions of both browsers now hide error messages from view because the typical user neither needs nor wants to see them. The only person who really needs to see the error messages is the programmer, because after a script has been fully debugged and made available on the Internet, it shouldn't have any errors (and even if there are errors, no one but the programmer can do anything about them anyway). Netscape and Microsoft's philosophy is to minimize the possible impact of a script's bugs on the user. Later this afternoon, I will show you how to view both Internet Explorer and Netscape Communicator error messages.



The best way to deal with syntax errors is to avoid them in the first place.Type carefully and double-check your scripts before running them to make sure that everything is in order. For example, make sure that you have avoided using reserved words as variable names , and do not forget to match up all opening and closing parentheses and braces. Remember to separate the attributes of the various loop statements with commas (except for the for statement, which uses the semicolon to separate its arguments).

Often the error messages tell you everything that you will need to know to find and correct problems. In addition to a brief problem description, the error message may even display the actual portion of code that caused the error. For example, if you attempt to load the following HTML page, an error will occur.

 1.  <HTML> 2.    <HEAD> 3.      <TITLE>Script 5.3 - Sample syntax error</TITLE> 4.    </HEAD> 5.    <BODY> 6.      <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript"> 7.      <!-- Start hiding JavaScript statements 8.        var testColor = "blue"; 9.        if (testColor == "blue" { 10.         document.write("We have a match"); 11.       } 12.     // End hiding JavaScript statements --> 13.     </SCRIPT> 14.   </BODY> 15. </HTML> 

Can you spot the error by eyeballing the script? The script consists of only a few lines of code, but the error still may not jump out at you. When I loaded this script, Netscape reported the following error message:

 Error: missing ) after condition Source File: file:///D:/JavaScripts/Script%205.3.html Line: 9, Column: 30 Source Code:        if (testColor == "blue" { 

Similarly, when I loaded this HTML page using Internet Explorer, the following error occurred.

 Line: 9 Char: 31 Error: Expected ')' Code: 0 URL: file://C:\Documents and Settings\Jerry Ford\Desktop\ Script 5.3.html 

With this information in hand, the job of debugging the script is much easier. As you can see, several very useful pieces of information were provided in the error messages provided by both browsers.

  • Line number on which the error occurred : line 9

  • Error message itself : missing ) after condition or Expected ')'

  • Error text (the actual line of code that generated the error) : if (testColor == "blue" {



To better show the value of the line number information provided in the error message, I added line numbers to the left of the previous example.These numbers are not part of the sample code that you normally type.When you are looking for a JavaScript editor, you may want to look for one that automatically provides line numbering.

As you can see, the error message indicates that a right parenthesis is missing on line 9. If you look at the error text portion of the error message, you will see where the ) should have been inserted, as demonstrated here:

 if (testColor == "blue" )) {   document.write("We have a match"); } 

Runtime Errors

A runtime error occurs as a result of an attempt by your script to do something that is against the rules. For example, if a script attempts to reference an undeclared variable or call a function that has not yet been defined, a runtime error will occur. Other examples of runtime errors include using JavaScript commands incorrectly. The following script will produce a runtime error when it is loaded by the Web browser:

 1.  <HTML> 2.    <HEAD> 3.      <TITLE>Script 5.4 - Sample runtime error</TITLE> 4.    </HEAD> 5.    <BODY> 6.      <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript"> 7.      <!-- Start hiding JavaScript statements 8.        myFunction(); 9.        function Myfunction() { 10.         document.write("Hello World!"); 11.       } 12.     // End hiding JavaScript statements --> 13.     </SCRIPT> 14.   </BODY> 15. </HTML> 

If you load this HTML page using Netscape Communicator, the following error will occur:

 Error: myFunction is not defined Source File: file:///D:/JavaScripts/Script%205.4.html Line: 8 

This error message tells you the line number where the browser thinks the error occurred and gives you a brief description of the error. In the preceding example, I intended to create and call a function named myFunction() .

Even though the error message points me to line 8, the actual error is on line 9 where I mistyped the function name as Myfunction() .



As the previous example demonstrates , the line number in the error message is not always accurate, but generally speaking, it comes pretty close to pinpointing the error. If the line indicated in the error message does not contain the error, you often will find it within a few lines before or after the line number stated in the error message.

Logic Errors

Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. Unfortunately, as far as JavaScript is concerned , the script is running well. Therefore, the browser won't generate an error message. The result is that you won't get any help in homing in on where the problem lies.

For example, the following script contains a logic error. The script was supposed to count from 1 to 10 and then terminate. However, when writing the for statement that controls the looping logic, I accidentally typed i-- instead of i++ . Instead of starting at 1 and going to 10, the script starts at 1 and counts backwards . Because the value of i never reaches 11, the script enters into an endless loop and never stops running. Although the script did exactly what it was told to do, it did not do what I intended it to do.

 <HTML>   <HEAD>     <TITLE>Script 5.5 - Sample logical error</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements        document.write(" Let's count from 1 to 10 <BR>")       for (i=1;i<11;i--) {         document.write(i + "<BR>")       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Another common example of a logic error is one that everybody gets wrong and involves the misuse of the assignment operator in place of the == comparison operator. For example, the following script displays the "We have a match" message even though the values of the apples and oranges variables are not the same. Clearly, this is not the logic I intended. When I rewrote the if statement as if (apples == oranges) and loaded it, the example worked as expected, and the "We do not have a match" message was displayed.

 <HTML>   <HEAD>     <TITLE>Script 5.6 - A second sample logical error</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       apples = 5;       oranges = 15;        if (apples = oranges) {         document.write("We have a match");       }       else {         document.write("We do not have a match");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 



One of the ways I could have debugged the preceding example would have been to add a checkpoint in the script just before the if statement. A checkpoint is a statement that displays the value of a variable so that you know what it has been set to. I will describe this debugging technique in more detail in a few minutes.

Habits of Highly Effective Programmers

Before I delve further into the discussion of debugging your scripts, I thought I'd provide you with a few tips that you can use to reduce the number of errors in your scripts and that can make the debugging process a little easier.

  • Remember to use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code. Comments make it much easier for others to follow behind you and for you to understand your own code months or years later.

  • Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.

  • Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort. Simplify your design by assigning only one task to a function.

  • Declare functions and variables at the top of your scripts. This approach makes those elements easy to find and modify, and is a lot less confusing than embedding them throughout different portions of lengthy scripts. This technique also helps to ensure that the functions and variables are defined before they are referenced.

  • Be consistent in the way you name variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.

  • Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.

  • Do not assume that your script is bug free just because it ran once without an error. Make sure that you test the script using different browsers and, if possible, with different versions of the same browser.

  • Make sure that you test your script using browsers that do not support JavaScript to ensure that your script properly provides alternative content. Try disabling support in your browsers for things such as frames to make sure that all browsers display your information as you intend it to be displayed.

  • Test all possible scenarios. This includes testing with good and bad data. If your pages have forms, enter invalid data and check to make sure that the validation routines work as you think they will. Test every link and click on every button.

  • Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.

  • Load your pages using different resolutions to make sure that they look as you expect them to at any size. Also try resizing your browser windows to see how your HTML pages look at different sizes.

  • Test every event handler to ensure that it executes as expected.

  • Declare variables explicitly using the var keyword.

  • Use descriptive variable and function names and avoid using single-character names.

  • Pay attention when using object names. Core JavaScript objects begin with capitalized letters (for example, Array, Boolean, Date, Function, Math, Number, Object, RegExp , and String ).

  • Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double). If you want to show quotation marks as part of the text message, embed them inside quotation marks of the alternate type (for example, place single quotation marks inside double quotation marks and vice versa).

Using Checkpoints

One very simple debugging technique is to place checkpoints in your script when you are writing and testing it. You can do this by taking advantage of the document object's alert() method to display the value of variables before and after they are evaluated or changed within the script to make sure that they are being set properly. Another use for checkpoints is to monitor the execution flow of your scripts to make sure that they are executing in the order you anticipate. For example, you can place an alert() statement in every function to display a message each time the function is called.


Alternatively, you can display a message in the current window using the document. write() method or open up a new window and write to it. It really does not matter which of these checkpoint techniques you use. Some may work better than others, depending on the circumstances.

Just remember one important thing: Save your visitors some frustration by remembering to remove or comment out all your checkpoints when you are done testing.

Test Before You Write

One of the most difficult things about programming in any language is figuring out the right syntax for a command that you want to execute in your script. One really neat trick you can use in Netscape Communicator or Internet Explorer is to type javascript: followed by the statement you want to test in the browser's URL field, as demonstrated in Figure 5.3.

Figure 5.3. You can type JavaScript commands and statements into the browser's URL field to test their results before you use the statements in your scripts.


Trapping Errors with onError

A JavaScript error event is triggered every time a script encounters a problem loading a window, frame, or image. A JavaScript onerror event handler routine can be set up to handle these situations. Three arguments are passed to the onerror event handler automatically:

  • Error message

  • URL information

  • Line number

The following script demonstrates how to write a function you can place in any of your scripts to display information associated with an occurrence of the error event. A function named ErrorTrap() is defined in the head section of the page; the function accepts three arguments. These arguments correspond to the three arguments that are automatically passed to the onerror event handler. The ErrorTrap() function then formats the error information in an alert pop-up dialog box. The statement onerror = ErrorTrap in the script in the head section tells the browser to call the function for any error event.

 <HTML>   <HEAD>     <TITLE>Script 5.7 - Capturing errors with the onError event handler</TITLE>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       function ErrorTrap(msg,url,lineNo) {         window.alert("Error: " + msg + "\nLine: " + lineNo + "\nULR: " + url);       }       onerror = ErrorTrap;     // End hiding JavaScript statements -->     </SCRIPT>   </HEAD>   <BODY>      <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       document.wrrite("");     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 5.4 shows the pop-up dialog box that is displayed as a result of loading this script. As you can see, all the error information is displayed and, in this example, it points you to the exact location of the problem.

Figure 5.4. The onerror event handler can be used in conjunction with the document object's alert() method to display debugging information.




You may have noticed that I used the \n character in the alert() statement to format the message output.This special formatting character causes a carriage return and is used to exercise control over how text is laid out in pop-up dialog boxes.

Internet Explorer Error Messages

Internet Explorer can suppress or display JavaScript error messages. This feature is configured on the Advanced property sheet on the Internet Options dialog box (see Figure 5.5) found in the Tools menu. By default, Internet Explorer 6 does not display JavaScript error messages. However, you'll probably find it handy to turn it on when you are creating and testing your JavaScripts. To enable this feature, select the Display a Notification About Every Script Error check box and click on OK.

Figure 5.5. Configuring Internet Explorer to display script errors automatically when they occur


The next time you load a Web page that contains a JavaScript error, you will see an Internet Explorer error dialog box similar to the one shown in Figure 5.6. As you can see, you can control the amount of information that is displayed by clicking on the Hide Details button.

Figure 5.6. Viewing all the details of an Internet Explorer error message


You can safely prevent the display of Internet Explorer error messages by clearing the Display a Notification About Every Script Error option and clicking on OK without losing convenient access to error information.

Instead, when an error is encountered , a small alert icon is displayed in the lower-left corner of the browser, as shown in Figure 5.7. Double-click on the icon to view the error dialog box.

Figure 5.7. When error notification is enabled, you can view Internet Explorer script error messages by double-clicking on the alert icon in the status bar.


Working with the Netscape JavaScript Console

Netscape comes with an integrated JavaScript tool known as the Netscape JavaScript Console. Unfortunately, there is no equivalent tool built into Internet Explorer. As a result, you may find that Netscape Communicator is the better browser to work with when debugging your JavaScripts. Netscape Communicator sends all error messages to the JavaScript Console.



When I am ready to do some serious debugging, I open the JavaScript Console and leave it displayed at all times.This makes it easier for me to view error messages.

The Netscape JavaScript Console, shown in Figure 5.8, is organized into two sections. The lower section displays a scrollable list of error messages. This section enables you to view current and previous errors. You can open the JavaScript Console at any time by typing javascript: in Netscape Communicator's URL field and pressing Enter. I think that you will find the Console's running history of errors very helpful but, if you prefer, you can click on the Clear button to clear out the messages in the display area.

Figure 5.8. Netscape Communicator provides a built-in JavaScript debugger that allows you to view error messages and test command syntax.


Testing JavaScript Statements

The top section of the JavaScript Console contains the Evaluate field, where you can type JavaScript statements and view their results. For example, Figure 5.9 demonstrates how to use the JavaScript Console to test the syntax of two JavaScript statements. The first statement defines a variable, and the second statement displays the value assigned to the variable using the alert() method. Note that in order for this to work the two commands must be separated by a semicolon.

Figure 5.9. You can type JavaScript commands into the Netscape JavaScript Console to test their results.


You also can use the Evaluate field to test JavaScript expressions and to perform mathematical calculations to make sure that your formulas will return expected results before you incorporate them into your scripts.

For example, the following text demonstrates how to test the syntax of a function and its statements. As you can see, the statement tests a small function named DisplayMsg() by calling it and passing a single argument. When this statement executes, you'll see an alert dialog box appear.

 function DisplayMsg(var1) { window.alert(var1) }; DisplayMsg("Hi"); 

The next example contains three statements. The first statement defines a variable, the second statement changes its value, and the third statement displays an alert dialog box if its conditional test evaluates to true .

 var oranges = 5; oranges = oranges + 5; if (oranges < 12) window.alert("Order more oranges"); 

[ LiB ]

Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84 © 2008-2017.
If you may any questions please contact us: