JavaScript Debugging Techniques with Firebug
By Akash Mehta2008-04-20
Debugging logic errors
We now have the following code:
<html>
<body>
<script>
var status = 25;
var port = 80, host = "google.com";
function Connect(status, host) {
// do some ajax
this.do_something = function(host, port) {
if (port == 60) {
alert("Good, port 80 - standard http");
} else {
alert("Bad, something nonstandard");
alert("this.host is " + this.host);
}
}
}
var connection = new Connect(status, host);
connection.do_something(host);
</script>
</body>
</html>
There are no errors caused, but we are still seeing the wrong set of alert boxes. This is most likely a logic error, because the code is doing something when it should be doing something else, and it is doing this at the if (port == 60)
condition. We could put in an alert or some other debug code to show us
the value of the pot variable, or we could use Firebug.
Open up Firebug and move to the "Script" tab. Find the line with the if (port == 60) on it, and click once in the beige margin at the left end of the line, to the left of the line number.
This will create a red dot, representing a breakpoint, in the margin on that same line. Now, refresh the page and the line will be highlighted in yellow, with an arrow on top of the red breakpoint dot. Hover your mouse over the "port". You should see the following:

Here, the JavaScript interpreter has paused at our breakpoint. We can choose to allow it to continue by clicking the blue arrow at the top. For now, however, we can inspect the value of any variable or expression in the current scope. Here, by hovering over port, it shows us that port is set to 80, as it should be. This is contrasted with our condition, checking if it is set to 60.
Clearly this is a logic error, and can be corrected by changing the 60 to 80 in the condition. We make this change, remove our breakpoint by clicking on it once again (click on the red dot and it will disappear momentarily), refresh the page, and the correct alert box ("Good, port 80...") appears.
This particular logic error could have been corrected on sight, however debugging more complex issues (especially where you compare one variable to another variable) is greatly simplified when using Firebug. To check the value of other expressions, we can use the watches, which "watch" the value of a variable so that we can see it at a glance at each breakpoint.
Tutorial Pages:
» Understanding JavaScript errors
» General debugging
» JavaScript debugging tools
» Debugging syntax errors
» Debugging runtime errors
» Debugging logic errors
» Further reading
