Java Reference
In-Depth Information
However, the if statement's condition must also be in parentheses. Not only is the initial parenthesis
missing, but there is one more closing parenthesis than opening parentheses. Like curly braces, each
opening parenthesis must have a closing parenthesis. The following code is correct:
if ((myVariable + 12) / myOtherVariable < myString.length)
It's very easy to miss a parenthesis or have one too many when you have many opening and closing
parentheses.
Using Equals (=) Rather than Is Equal To (==)
Consider the following code:
var myNumber = 99;
if (myNumber = 101)
{
alert(“myNumber is 101”);
}
else
{
alert(“myNumber is “ + myNumber);
}
You'd expect, at fi rst glance, that the alert() method in the else part of the if statement would exe-
cute, telling us that the number in myNumber is 99 , but it won't. This code makes the classic mistake of
using the assignment operator (=) instead of the equality operator (==). Hence, instead of comparing
myNumber with 101 , this code sets myNumber to equal 101 . If you program in Visual Basic, or languages
like it that use only one equals sign for both comparison and assignment, you'll fi nd that every so often
this mistake crops up. It's just so easy to make.
What makes things even trickier is that no error message is raised; it is just your data and logic that will
suffer. Assigning a variable a value in an if statement may be perverse, but it's perfectly legal, so there will
be no complaints from JavaScript. When embedded in a large chunk of code, a mistake like this is easily over-
looked. Just remember it's worth checking for this error the next time your program's logic seems crazy.
Using a Method as a Property and Vice Versa
Another common error is where either you forget to put parentheses after a method with no parameters,
or you use a property and do put parentheses after it.
When calling a method, you must always have parentheses following its name; otherwise, JavaScript
thinks that it must be a pointer to the method or a property. For example, examine the following code:
var nowDate = new Date();
alert(nowDate.getMonth);
The fi rst line creates an instance of the Date reference type. The second line attempts to call the getMonth()
method of the newly created Date object, except the parentheses are missing. The following is the cor-
rected code:
var nowDate = new Date();
alert(nowDate.getMonth());
Search WWH ::




Custom Search