GEOG5870/1M: Web-based GIS A course on web-based mapping

Debugging JavaScript

When writing code in JavaScript, you will soon come across problems: either your code does nothing, or it does something that wasn't what you expected. However, your browser will typically give you little by way of explanation as to what has gone wrong, although error handling is clearly something which should be browser-dependent as that's where the code is running. On this page, we look at two approaches to error handling and debugging.

try...catch

JavaScript provides a mechanism for recovering from errors, in the form of the try-catch statement. Any statement (or a set of sub-statements grouped using '{}' ) can be placed inside a try clause; if part of that code hits an error (or "exception"), then execution of the try statement will cease, and instead the statement in the catch clause will be executed. An example is shown below. Code "a" shows the generic form of the statement, whilst "b" gives a specific example.

a) Generic form
try {
   // code that might fail
} catch (err) {
   // error handling code
}

b) Example usage
try {
   Document.write("Hello");
} catch (err) {
   alert("There was an error:" + err.message);
}

In the example shown in "b", above, we are attempting to use the method document.write(), but have made a typo – we have started with an upper case letter. On its own, this would probably lead to the execution halting without anything being displayed. However, by placing it in the try-catch statement, we can 'catch' the error, and do something more useful. In this case, we use the alert() method to display a notice to the user, and execution will commence from the next statement. The catch clause contains a parameter – a term placed in parentheses after the keyword – in this example 'err'. This is the name used as an identifier for an error object. The error object has a limited number of properties, including the message property, as used here.

The try-catch statement can be used where there is a reasonable expectation that code might fail; for example, if a JavaScript program is trying to make a connection to a remote source in order to retrieve some data, and we cannot rely on that host to be up and running as expected.

Browser Consoles

Obviously try-catch blocks are great for dealing with issues you're expecting, but how do you find out what is wrong with code that isn't working? The common way is to use the web browser's debugging options. Most browsers have two useful additions. Firstly, they will report errors with running code, and flag the line that is failing first (they may also show subsequent failures if the code runs on regardless). The common place for this to happen is the "console" – a (usually hidden) window where messages appear for developers (though some browsers have a full and separate interface for the debugger that allows more control over how debugging is done). Secondly, you can dump messages to the console yourself. In a minority of cases, you could use alert to pop up a sequence of messages as a script progresses, but the console is cleaner: it doesn't require anyone to shut down a message box, and can be safely left in during public alpha or beta testing for diagnostics. Essentially it is the JavaScript equivalent of System.out.println() in Java, or print() in Python, but with the advantage that it is usually hidden from users.

With most browsers, you write to the console, thus:

console.log("message " + variableValuesEtc);

In most browsers, the console is part of a suit of "Developers' Tools", which can be accessed by pressing the F12 key; however, here are some specific instructions for each:

Firefox

In Firefox, the JavaScript console can be found in the "Developers' Tools". Go to the Tools menu, then Web Developer and click Toggle Tools. This will bring up the developer tools, usually at the bottom of the browser window. You'll see there is a tab for the Console (and a more complicated interface for the debugger). You can also jump to this directly from the same menu that is used to Toggle Tools. To get rid of the tools, Toggle again, or use the "X" in the corner of the tools. Note that when you open it up, by default the console may show no outputs; when you open the console, you'll see a set of buttons appear below the tabs (indeed, they look like tabs themselves, but aren't). Toggling these buttons will turn on and off reporting on different issues, including CSS and JS (JavaScript). You may find you need to reload the page after toggling these on to see the messages.

Google Chrome

Google Chrome has it's set of developer tools and debuggers. Go to the menu (three vertical dots on the address bar), select More Tools and then Developer Tools. It has to be said that they have a bit of a tendancy not to show up, in which case, you might want to install Firefox as the easy solution.

Note that for security reasons Chrome will only run external JavaScript files from a proper webserver, meaning you can't just open files you're developing from the local harddrive – you have to go via a proper URL. There is a way to turn this off: run Chrome from a command prompt or shortcut thus:
chrome.exe --allow-file-access-from-files

Internet Explorer

Internet Explorer's Developer Tools can be reached from the "cog" menu. One nice thing about IE is that you can change the browser so it runs as if it were older (and in some cases newer) versions of the browser: see the dropdown list on the right of the Developer Tools toolbar.


Task: Debugging exercise

The code below shows a slightly modified version of the Fibonacci sequence code shown on the previous page. There are two differences. Firstly, the HTML page loads a differently named JavaScript file, and secondly, there is an error in that JavaScript file: when we try to write out our new value of f_n, there is a typo, and we have used 'fn' instead.

HTML document fib2.html:
<html>
<head>
<title>Fibonacci sequence</title>
 <script type="text/javascript" src="fib2.js"></script>
</head>

<body>
Page body text
</body>

</html>

External JavaScript file fib2.js:
/*
 * Calculating the first few numbers of the Fibonacci sequence
 *
 * f(n) = f(n-1) + f(n-2)
 */

var count;
var f_2 = 0;
var f_1 = 1;
var f_n;

document.write("<h1>Fibonacci numbers</h1>");
document.write("<ol>"); // start an html list

// Write the start of the sequence
document.write("<li>" + f_2);
document.write("<li>" + f_1);

// Loop to calculate some more values
for (count=1;count<10;count++) {

   f_n = f_1 + f_2; // Calculate f(n)
   document.write("<li>" + fn); // Write the latest value

   f_2 = f_1;
      // Next iteration, f(n-2) has the value of the current f(n-1)
   f_1 = f_n;
      // And f(n-1) will have the value of the current f(n)
}

document.write("</ol>");

A copy of the buggy program is linked here: fib2.html / fib2.js

If you load that page, you will find that the program has failed. The first two values of the sequence have been printed, but no others. What has happened? We can use the debugger and console to help find this out.

How do you comfort a JavaScript bug? Answer: You console it (ElijahManor). Ha. Ha ha... Hurrr.



[ Next: Example programs]
[Course Index]