“ Errors in my script? Impossible!”

A JavaScript expert can make mistakes, even if they are simply annoying typos. In particular when a code expands to thousands of lines, the chance of something going erroneous becomes much greater. In proportion, the difficulty in finding these mistakes, or bugs, also increases.

When something does not work right in computer programs, it is called a bug. Understandably enough, ridding your scripts of bugs is called “debugging”. This topic is important enough for any serious JavaScript writer to devote an entire book to it.

We are only human, after all, and making mistakes is part of our nature. We also tend to make the same kind of mistakes; some of us even tend to make the same mistakes over and over, never learning from them. This article will focus on common coding errors those you may encounter when writing JavaScript programs. Knowing about them probably won’t keep you from making them yourself, but being aware of the kinds of mistakes that can happen might help you track down the bugs in your scripts.

Some Common Coding Mistakes— Any Programmer Can Make:

1. Undefined Variables: JavaScript is quite relaxed during defining variables prior assigning values to them. For instance, the following line will implicitly create a new variable xyz and assign it to the value 120.

xyz = 120;

Although strictly speaking, we should define the variable explicitly.

var xyz= 120;

Note: Actually, whether you use the var keyword has a common consequence on the scope that the variable has, so in fact it is always better to use the var keyword.

However, if a variable is actually used before it has been defined, an error message will arise.

Example:

alert(xyz);

the above code will cause the error shown in below if the variable xyz has not been previously defined (explicitly or implicitly).

Line:10
Char: 1
Error: ‘xyz’ is undefined
Code: 0
URL: file://C:\example.htm

In addition, we must remember that function definitions also have parameters, which, if not declared correctly can lead to the same type of error.

Take a look at the following code:

function Quizreset (numOfQustions, timLimit)
{
     leftTime=timeLimit;
     totalQAsk= numOfQuestions;
     currentQNum= -1;
     quesAsked =new  Array();
     numberOfQAsked =0;
     numberOfQCorrect =0;
   }

When this Quizreset( ) function is called, we will get an error message such as

Error: ‘numOfQuestions’ is undefined
Error: ‘timeLimit’ is undefined

The error here is two typing mistakes in the definition of the function Quizreset(). The first parameter contains a typo that should be numOfQuestions instead of numOfQustions. And the second parameter should be timeLimit instead of timLimit .

2. Single Equals Instaed of Double equals in Comparison Expressions: This mistake is so common that you are bound to make it at least once. JavaScript expects to read double equal signs in a comparison expression instead of one. Therefore, the following JavaScript expression is an error:

if(testVar= "abc")

Like C, C++, and Java, JavaScript insists you to place two equal signs in the expression such as:

 if (testVar=="abc")

3. Improperly Nested if statements: Many scripts use lots of if expressions. To provide greater flexibility, these if statements are sometimes nested inside one another. The intent is to perform additional tests should the first return true or false.

Here is an example:

if (testVar1==1){
        if(testVar2==1)
                //do this if testVar1=1 and testVar2=2;
        //do this if only testVar1=1;
}else
        //do this if testVar1<>1;

Eagle eyes will see that if testVar1 does not equal to 1 , the inside test (testVar2==1) is never performed. Be sure this is what you want. If it isn’t, this logic error is hard to spot.

4. Sending Output to the Script Document: The document.write() method writes over any text you have in your document, including text created using HTML markup. The following lines produce an error (“Test is not defined”) because JavaScript writes over the form before it has a chance to set a value on it:

<SCRIPT>
document.write ("Welcome<P>");
document.test.box.value = "Welcome Dear";
</SCRIPT>
<FORM NAME="Test">
<INPUT TYPE="Text" NAME="box">
</FORM>

Avoid using the document. write () method to write in a document that contains HTML you want to keep.

5. Endless loops Lockup Netscape: An endless loop is a for or while that does not break out. This causes JavaScript to execute the loop over and over again. Here’s an example of an endless loop(there’s no expression in the second argument for terminating the loop):

for (Number=0; Number; Number++){
     ............................   
    }

JavaScript prevents a complete runaway train by limiting the number of loops to a million; which takes about 30-90 seconds for the loops to be processed, depending on your computer processor speed. At that point, JavaScript displays an error message box that asks “Lenghty JavaScript still running. Continue?”

To break this endless looping you have to click “Cancel” button on the error dialog box.

6. Missing or Poor Placement of { and } Block Character: You must exercise caution that you provide the proper { and } characters to define the blocks of the if statements. Otherwise, your script is bound to behave in truly strange ways!

Consider the next example.

TestVar1=21;
if(TestVar1==11)
    alert ("TestVar1=11");
    alert("Congratulations");

 

Suppose you forgot to use the { and } characters to block out the ( TestVar 1 ==11 ) if expression. What happens? JavaScript assumes that after the first line, all the following code should be executed whether or not the TestVar1==11 expression evaluates as true. The user sees the “Congratualtions” message either way.

Hence, the script should be written as:

TestVar1=21;
if(TestVar1==11){
    alert ("TestVar1=11");
    alert("Congratulations");
}

7. Missing/Misplaced return Statement: The return statement at the end of a function tells JavaScript to exit the function and return to the calling statement-the command line that called the function in the first place. If the return is missing, JavaScript proceeds to the end of the function and returns anyway. There’s nothing wrong here, assuming the function does not return a value. But if the function returns a value, JavaScript automatically returns a null, which is a “blank” result. That could cause other parts of your script to malfunction.

The return statement is limited to use inside a function. The following code results in an error showing the message return used outside a function :

function exampleFunction(){
    ..................
}
return;

8. Stack overflow: A stack overflow is typically caused when you have repeatedly called the same function from within an “infinite loop” function, as here:

function testfunc(){
    testfunc();
}

The above lines generate an error message – stack overflow in testfunc.

JavaScript loops through about 400-500 times before it runs out “stack space” and return the error.

9. Unterminated and Nested Comment: JavaScript likes to see a */ pair for every /* when defining comments. This results in an error:

/*This is an unterminated comment

To fix this problem, add a */ to complete the comment. Note that the // form of a comment automatically terminates at the end of the line (marked by a hard return in the JavaScript code).

In addition, JavaScript does not like you to nest /* mult-iline comments. The following results in an error. To fix the error remove the second /*.

/*This is a test /* of a nested comment*/

10. Wrong use of JavaScript object, method, or property: Consider the error message:

Error: xyz is not a function

Note: Here xyz refers variable text that JavaScript provides, such as an object, function, or variable name in the rest of the article.

You typically see this error when you try to use a JavaScript object, method, or property as a function. Note that there is some inconsistency in the terminology used by JavaScript. JavaScript supports a number of statements called functions: these include eval, parseInt, and parseFloat. These are functions because they are not connected to any object (if they were, they would be called methods).

However, JavaScript also considers many methods to be functions because they alter an object in some way and return the change to the object. This error message is most common when you attempt to use a method for an object that does not support that method.

As an example, the click () method is used with several form objects, notably push buttons, checkboxes, and radio buttons. The following line results in a “is not a function” error message because the click () method cannot be used with a string:

"my string.click()";

11. Wrong Use of an Object in with Statement: Consider the error message:

Error: xyz can not be used in a with statement

This error indicates you have attempted to sue an object with the with statement, and the with statement is not supported for that object. Typically this occurs when you have misspelled the name of an object and JavaScript can’t find it. For instance, the following script results in an error because the name of the text box is “textbox1”, not “textbox”.

<HTML><HEAD>
<TITLE>This is a test example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function test (){
         with (document.forms[0].textbox){
                alert (value);
         }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="testform">
<INPUT TYPE="button" NAME="button1" VALUE="Start" onClick="test(this.form)"><P>
<INPUT TYPE="text" NAME="textbox1"><P>
</FORM>
</BODY>
</HTML>

12. Wrong use of new Keyword: You see the following error if you try to use the new keyword with an object that you can’t “instantiate”(create a new instance, or copy, of ).

Error: xyz can not be used in a with statement

For example, the error message appears in the following because you cannot use the new statement to create a new window object:

test = new window;

13. Type mismatch error : Consider the following code:

testVar1=51;
testVar2="normal";
resultVar= testVar1 * testVar2;

The code generates an error message while you try to run the code :

Error: testVar2 is not a numeric literal

This error occurs when you attempt to use a non-numeric value as a number. For example, JavaScript cannot complete the expression on the third line because it cannot multiply a number by a text string.

A number of other types of errors are not essentially bugs in your JavaScript code; however, in fact exceptions to the normal circumstances that cause the code to fail. These types of mistakes could be harder to spot in large chunks of code. Furthermore, the corresponding error messages can be confusing. These types of errors can still be considered for, as you would see how to manage them by exception handling in the next section.