Finding JavaScript bugs

See more about:

Where are we?

You’re learning how to do some basic stuff with JavaScript. But what happens when your code doesn’t work?

This lesson’s goals

Learn:

  • Syntax bugs happen when you type something the browser doesn’t understand, like alrt().
  • Use Firefox’s error console to track down syntax errors.
  • Logic errors are when you tell the browser to do the wrong thing.
  • Use alert() statements to track program execution. If alert() messages are supposed to show up, but don’t, you know what code is not executing.
  • Use alert() statements to look at the values of variables.

Types of bugs

There are two types of errors:

  • Syntax bugs, where you give the browser an instruction it cannot understand.
  • Logic bugs, where you tell the browser to do the wrong thing.

The first type is easier to find and fix.

Syntax bugs

Syntax errors are when the browser can’t understand your instructions. For example, suppose a human asks you to:

Grag the blint flakengargle.

The words don’t make any sense.

Here’s a JavaScript example. Suppose you put this on a page:

alrt('Dogs are great!');

The browser won’t understand alrt. You meant this:

alert('Dogs are great!');

Most syntax errors are simple typing errors, like this one.

Use the right editor

Up to now, you may have been using Notepad++. It’s a good editor to start with. Easy to use. It works just fine.

But it’s time to move on.

Install Netbeans, an integrated development environment (IDE). An IDE is a collection of tools to help people write code. The tools include an editor that, get this, checks for errors!

Here’s some code in Notepad++.

Code in Notepad++

Figure 1. Code in Notepad++

Looks OK. Here’s the same code in Netbeans.

Code in Netbeans

Figure 2. Code in Netbeans

Netbeans can analyze your code, and flag errors. This will save you a lot of time and frustration.

So, go to netbeans.org. Download the PHP bundle, and install it. Remember, the PHP bundle.

Netbeans is fairly easy to use, but there’s one hitch in getting started. Netbeans has the concept of projects, a collection of related files. You need to set up projects to work with Netbeans.

Don’t worry. It’s easy. Suppose you’ve been working on CoreDogs exercises. You created this in your Documents directory:

Your directories

Figure 3. Your directories

You’ve been putting your CoreDogs files in the CoreDogs directory:

Files in your directories

Figure 4. Files in your directories

You’ve been using Notepad++ to work on these files.

All you have to do is tell Netbeans to put your files into a project, and you’re ready to go. Let’s see how.

Here’s Netbeans without any projects.

Netbeans, empty

Figure 5. Netbeans, empty

Create a new project.

New project

Figure 6. New project

You’ll see a screen like this:

New project form

Figure 7. New project form

Tell it that you want to create a PHP project from existing sources:

Create a PHP project from existing sources

Figure 8. Create a PHP project from existing sources

Er, you installed the Netbeans PHP bundle, right?

PHP is a language for programs that run on Web servers. It’s covered in CoreDogs, in the ServerCore book.

The next Netbeans form is like this:

Name and location form

Figure 9. Name and location form

Select the directory you’ve been using for your exercises:

Select your directory

Figure 10. Select your directory

Click the Finish button. Netbeans will create your project.

Open the Sources, and you’ll see your files:

Your files in Netbeans

Figure 11. Your files in Netbeans

Double-click on a file to open it. Right click to create a new file:

Creating a new file

Figure 12. Creating a new file

If you look at your directory in Windows Explorer, you’ll see that Netbeans added a new subdirectory:

Netbeans project subdirectory

Figure 13. Netbeans project subdirectory

Don’t delete it, or you’ll have to make the project again.

So, now you’re running Netbeans. There are other good IDEs, like Aptana.

These IDEs are good, but they’re not perfect. For example, check the code in Figure 2. There’s an error in the JavaScript that Netbeans didn’t flag as an error. The yellow in line 11 says that Netbeans thinks there might be something funny going on, but there’s no error icon.

You’ll need other tools to squash those bugs.

The error console

When a browser finds a syntax error in your JavaScript, it will do two things:

  • Stop running your code.
  • Tell you about the error. It will show an error message.

If you can find the error message, you can fix the error. But the browser won’t show an error message in the middle of a Web page. You have to know where to look.

Different browsers show errors in different places. Let’s talk about Firefox, CoreDog’s official browser. Firefox is better at helping you find syntax errors than Internet Explorer. You’ll find that Firefox is a better choice for Web work. If you haven’t already, download Firefox and start using it.

Firefox shows errors in its error console. The error console collects all the error messages from all the pages Firefox shows.

Open the error console from the Tools menu:

Opening the error console

Figure 14. Opening the error console

Try it now. Your menu will look different, depending on the add-ons you have installed.

Here’s what I saw when I opened my error console just now:

The error console

Figure 15. The error console

Yikes!

Don’t panic. It’s normal to have a bunch of stuff showing.

You want to start with a clean slate, so you see error messages from your code, and not from other people’s pages. Click the Clear button. This erases all the messages.

OK. Now let’s load a page with an error, and see what happens. Here’s the code you’ll try to run:

$(document).ready(function() {
  alert("About to try a broken line of JavaScript.");
  alrt("This line is broken");
  alert("Just tried to run a broken line.");
});

Figure 16. Broken JavaScript

To try it, click on this link.

Now check the error console. This is what I see:

Error message

Figure 17. Error message

Sometimes it’s hard to know what an error message means. The browser doesn’t say, “Hey! You typed alert wrong.” Because it doesn’t know that. Maybe you really meant to type alrt, but forgot to tell the browser what alrt means. So you might have to think a bit to figure out what the problem is.

You can Google error messages, if you want. For example, you could search for:

javascript error “is not defined”

CC
CC

When I tried the page, I saw an alert box for “About to try a broken line of JavaScript.” But I didn’t see one for “Just tried to run a broken line.” This line looks right to me:

alert("Just tried to run a broken line.");

Kieran
Kieran

The line is right. But the browser stops as soon as it finds a syntax error. So it never gets to that line.

When error messages appear

The error message we just saw showed up as soon as the page was loaded. Why? Because the bad line was in the $(document).ready() event. Code there runs when the page loads.

Sometimes errors might not appear until later. Let’s try this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Broken again</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#button_of_doom").click(function(){
          alert("About to try a broken line of JavaScript.");
          alrt("This line is broken");
          alert("Just tried to run a broken line.");
        });
      });
    </script>
  </head>
  <body>
    <p>Click the button to make an error message.</p>
    <p>
      <button type="button" id="button_of_doom">Doom</button>
    </p>
  </body>
</html>

Figure 18. More broken JavaScript

The broken JS is line 11. This time, it’s inside the $("#button_of_doom").click() event. The browser won’t try to run line 11 until the button is clicked.

Let’s give it a try. First, clear the error console. Now click this link to load the page.

Check the error console. It should be empty. The browser hasn’t tried to run the bad line yet.

Click the button, and then the OK button on the dialog box that appears. Now check the error console again. There’s the error message.

So, if your JavaScript program isn’t running:

  • Open the error console and clear it.
  • Reload your page, and check the error console. This will show you syntax errors the browser found when it tried to load the page.
  • Do the thing that isn’t working right (e.g., click the button that’s supposed to do a calculation but doesn’t). Check the error console.

Most syntax errors are simple typing errors. They’re easy to fix. But there’s another type of error: a logic error. Logic errors are usually more difficult.

CC
CC

Wow, finding bugs might be hard. Programming could get irritating.

Kieran
Kieran

Frustration is normal when doing computer work. You need ways of handling it. Know how to:

Or you could be like this guy.

The error console will help you fix syntax errors. Let’s move on to the second type of bug.

Logic bugs

Logic bugs are where the browser understands what you have told it, but you’ve told it the wrong thing. Sometimes these are just typing mistakes, but usually they’re thinking mistakes.

A problem with logic errors is that the browser won’t show an error message. The error console won’t help. You have to track down the error on your own.

Here’s a page with a simple logic error. You can try the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Square a Number</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#input_number").focus();
        $("compute_button").click(function() {
          input_number = $("#input_number").val();
          square = input_number * input_number;
          $("#square").text(square);
        });
      });
    </script>
  </head>
  <body>
    <h1>Square a Number</h1>
    <p>
      Type in a number, and I will tell you its square. For example,
      the square of 3 is 3 x 3 = 9.
    </p>
    <p>
      Number:
      <input type="input" id="input_number">
      <button type="button" id="compute_button">Compute</button>
    </p>
    <p>Square <span id="square"></span></p>
  </body>
</html>

Figure 19. Another broken page

See if you can find the problem by just looking through the code.

Don’t worry if you can’t spot the error. It’s easy to overlook, no matter how much you stare at the code.

alert()

One way to find errors is to add alert() statements, like this:

<script type="text/javascript">
  alert("Before the ready function");
  $(document).ready(function() {
    alert("Starting the ready function");
    $("#input_number").focus();
    $("compute_button").click(function() {
      alert("Starting the click function");
      input_number = $("#input_number").val();
      square = input_number * input_number;
      $("#square").text(square);
      alert("Ending the click function");
    });
    alert("Ending the ready function");
  });
</script>

Figure 20. Adding alert()s

I know when the alert dialogs should appear. I can run the page, and see whether what I expect to happen does happen. If it doesn’t, this will help me find the mistake.

Here’s when each alert dialog should appear:

  • Line 8: During page load, before any content appears.
  • Line 10: When the page loads and the content shows, but before the user can click on the button.
  • Line 19: Right after the dialog from line 10.
  • Line 13: After the user has clicked the button, but before any output has shown.
  • Line 17: After the output has been shown.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 21. Tracking down the problem

You can try the page.

OK, so the page shows the alerts for lines 8, 10, and 19, but not for lines 13 or 19. Line 13 should show a message when the user clicks the compute button. Maybe the code for the compute button is not being run.

Here’s the code that sets up the click event for the button:

$("compute_button").click(function() {

Aha! I see the problem now. Do you see it?

Compare this line to the corresponding line from an example in the last lesson.

$("#compute_tip").click(function(){

I missed the #! The code should be:

$("#compute_button").click(function() {

Without the #, the browser can’t find the button to tie the event code to.

Renata
Renata

Wow, all that trouble because of one missing character?

Kieran
Kieran

Yes. That’s quite normal in computer work. You need to be careful and patient.

You can try the fixed verion.

So, adding alert statements let us follow the execution of the JS. When we got something we didn’t expect, we were able to find the problem.

Showing variables

Sometimes that’s not enough. Here’s another version of the JS, with a different problem from the last one.

<script type="text/javascript">
$(document).ready(function() {
  $("#input_number").focus();
  $("#compute_button").click(function() {
    input_number = $("#input_number").val();
    square = input_number + input_number;
    $("#square").text(square);
  });
});
</script>

Figure 22. A different problem

Try the page. You get output this time, but it’s wrong:

Wrong output

Figure 23. Wrong output

If I add the same alert()s we had last time, I’ll find that everything appears just fine. All of the code is executing. But the output is wrong.

Hmm. Maybe I’ll check that the data is being read correctly, and the computations are done right.

I’ll add some more alerts:

<script type="text/javascript">
$(document).ready(function() {
  $("#input_number").focus();
  $("#compute_button").click(function() {
    alert("Starting the click function");
    input_number = $("#input_number").val();
    alert("input_number:" + input_number);
    square = input_number + input_number;
    alert("square:" + square);
    $("#square").text(square);
    alert("Ending the click function");
  });
});
</script>

Figure 24. alerts

Look at lines 12 and 13:

input_number = $("#input_number").val();
alert("input_number:" + input_number);

The alert() shows the value of a variable. I can compare it with what it should be.

Let’s run the code.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

Figure 25. Showing variable values

You can try the page.

So, we know that this line is causing the problem:

square = input_number + input_number;

Aha! The + should be *! Change it, and the page will work.

W00f!

Exercise: Debugging JavaScript

Fix the bugs in this page.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Review your code

Debugging takes time. Inserting alert statements, loading pages, etc.

A suggestion. Before you test your page for the first time, read over the code. Carefully. Take your time. You can find mistakes without having to use alerts.

Going deeper

Firebug is a debugging add-on for Firefox.

Summary

  • Syntax bugs happen when you type something the browser doesn’t understand, like alrt().
  • Use Firefox’s error console to track down syntax errors.
  • Logic errors are when you tell the browser to do the wrong thing.
  • Use alert() statements to track program execution. If alert messages are supposed to show up, but don’t, you know what code is not executing.
  • Use alert() statements to look at the values of variables.

What now?

You know how to grab data from text fields, and do things with them. But what if the user doesn’t type anything? Or says that his or her age is, say, -15?


How to...

Lessons

User login

Log in problems? Try here


Dogs