Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Debugging a Script

You should now have a good understanding of what can go wrong with JavaScript programs and the tools you have available to diagnose these problems. You can now try your hand at debugging a script.

Listing 17.2 shows a script I wrote to play the classic "Guess a Number" game. The script picks a number between 1 and 100 and then allows the user 10 guesses. If a guess is incorrect, it provides a hint as to whether the target number is higher or lower.

This is a relatively simple script with a twist: It includes at least one bug and doesn't work at all in its present form.

Example 17.2. The number guesser script, complete with bugs

<html>
<head>
<title>Guess a Number</title>
<script LANGUAGE="JavaScript" type="text/javascript">
var num = Math.random() * 100 + 1;
var tries = 0;
function Guess() {
var g = document.form1.guess1.value;
tries++;
status = "Tries: " + tries;
if (g < num)
    document.form1.hint.value = "No, guess higher.";
if (g > num)
    document.form1.hint.value = "No, guess lower.";
if (g == num) {
    window.alert("Correct! You guessed it in " + tries + " tries.");
    location.reload();
    }
if (tries == 10) {
    window.alert("Sorry, time's up. The number was: " + num);
    location.reload();
    }
}
</script>
</head>
<body>
<h1>Guess a Number</h1>
<hr>
<p>I'm thinking of a number between 1 and 100. Try to guess
it in less than 10 tries.</p>
<form NAME="form1">
<input TYPE="text" SIZE=25 NAME="hint" VALUE="Enter your Guess.">
<br>
<b>Guess:</b>
<input TYPE="text" NAME="guess1" SIZE="5">
<input TYPE="BUTTON" VALUE="Guess"  onClick="guess()">
</form>
</body>
</html>

Here's a summary of how this script should work:

Testing the Program

To test this program, load the HTML document into your browser. It appears to load correctly and does not immediately cause any errors. However, when you enter a guess and press the Guess button, a JavaScript error occurs.

According to Netscape's JavaScript Console, the error message is this:

Line 36: guess is undefined

Internet Explorer's error message refers to the same line number:

Line 36, character 1: Object expected

Fixing the Error

As the error message indicates, there must be something wrong with the function call to the Guess function, in the event handler on line 36. The line in question looks like this:

<input TYPE="BUTTON" VALUE="Guess"  onClick="guess()">

Upon further examination, you'll notice that the first two lines of the function are as follows:

function Guess() {
var guess = document.form1.guess1.value;

Although this may look correct at first glance, there's a problem here: guess() is lowercase in the event handler, while the function definition uses a capitalized Guess(). This is easy to fix. Simply change the function call in the event handler from guess to Guess. The corrected line will look like this:

<input TYPE="BUTTON" VALUE="Guess"  onClick="Guess()">

Testing the Script Again

Now that you've fixed the error, try the script again. This time it loads without an error, and you can enter a guess without an error. The hints about guessing higher or lower are even displayed correctly.

However, to truly test the script, you'll need to play the game all the way through. When you do, you'll discover that there's still another problem in the script: You can't win, no matter how hard you try.

After your 10 guesses are up, an alert message informs you that you've lost the game. Coincidentally, this alert message also tells you what's wrong with the script. Figure 17.3 shows how the browser window looks after a complete game, complete with this dialog box.

17fig03.jpg

Figure 17.3 The number guesser script's display after a game is finished.

As you can see from the alert message, it's no wonder you didn't win: The random number the computer picked includes more than 10 decimal places, and you've been guessing integers. You could guess decimal numbers, but you'd need a whole lot more than 10 guesses, and the game would start to lose its simplicity and charm.

To fix this problem, look at the statement at the beginning of the script that generates the random number:

var num = Math.random() * 100 + 1;

This uses the Math.random method, which results in a random number between 0 and 1. The number is then multiplied and incremented to result in a number between 1 and 100.

This statement does indeed produce a number between 1 and 100, but not an integer. To fix the problem, you can add the Math.floor method to chop off the decimal portion of the number. Here's a corrected statement:

var num = Math.floor(Math.random() * 100) + 1;

To fix the script, make this change and then test it again. If you play a game or two, you'll find that it works just fine. Listing 17.3 shows the complete, debugged script.

Example 17.3. The complete, debugged number guesser script

<html>
<head>
<title>Guess a Number</title>
<script LANGUAGE="JavaScript" type="text/javascript">
var num = Math.floor(Math.random() * 100) + 1;
var tries = 0;
function Guess() {
var g = document.form1.guess1.value;
tries++;
status = "Tries: " + tries;
if (g < num)
    document.form1.hint.value = "No, guess higher.";
if (g > num)
    document.form1.hint.value = "No, guess lower.";
if (g == num) {
    window.alert("Correct! You guessed it in " + tries + " tries.") ;
    location.reload();
    }
if (tries == 10) {
    window.alert("Sorry, time's up. The number was: " + num);
    location.reload();
    }
}
</script>
</head>
<body>
<h1>Guess a Number</h1>
<hr>
<p>I'm thinking of a number between 1 and 100. Try to guess
it in less than 10 tries.</p>
<form NAME="form1">
<input TYPE="text" SIZE=25 NAME="hint" VALUE="Enter your Guess.">
<br>
<b>Guess:</b>
<input TYPE="text" NAME="guess1" SIZE="5">
<input TYPE="BUTTON" VALUE="Guess"  onClick="Guess()">
</form>
</body>
</html>

Figure 17.4 shows the debugged example in action in Netscape 6, after a successful game.

17fig04.jpg

Figure 17.4 The number guesser example after a successful game.

Share ThisShare This

Informit Network