Debugging Scripts

JavaScript can be very frustrating when there is an error in the code. An error can cause an entire script
to run incorrectly, or not run at all. Debugging a script is usually time consuming!

Table of content:

  • Types of Errors
  • Items to look for when scanning the script
  • Find the logical errors

Types of Errors

There are two main types of errors: syntax error and logical error.
A syntax error is, for example, when you forget a semicolon, or mistype a word in your code.
A logical error is when the code is implemented incorrectly.

<input type="button" value="Click" onclick="analert() analert2()" />

In the code above the semicolon between the two function calls is very important because they are on the same line. In some cases, the error causes the browser to display an error message which might help you figure out what causes the problem.

Items to look for when scanning the script for errors

ItemAppearance
Missing semicolon;
Missing curly or square brackets{} []
Missing parentheses()
Missing single or double quote‘ “
MisspellingHoda instead of Honda, for example

Find the logical errors

Logical errors are very difficult to find because the syntax of the code is correct but not the way it is implemented.

x = 1;
y = 2;
while (x<=y) {
/* 
The problem is that x is never greater than y
An infinite loop is created
*/
	window.alert("Hi there!");
}

In the code above, the window.alert() will always happen because x is always smaller than y. To solve the problem we have to increase the value of x, or decrease the value of y, or both of them.

x = 1;
y = 2;
while (x<=y) {
	window.alert("Hi there!");
	x++;
}

In this example, the window.alert() will happen only twice because first x is smaller that y (1<2),and second, after x is increased by 1, it becomes 2 and x=y. The third time the x becomes 3 (which is greater than 2) so the
window.alert() won't appear.

Leave a Reply