Java Reference
In-Depth Information
Now you can see that the ending curly brace of the function is missing. When you have a lot of
if , for , or do while statements, it's easy to have too many or too few closing braces. This type of
problem is much easier to spot with formatted code.
incorrect number of Closing parentheses
Similarly, not having the correct number of closing parentheses can be problematic. Take a look at
the following code:
if (myVariable + 12) / myOtherVariable < myString.length)
Spot the mistake? The problem is the missing parenthesis at the beginning of the condition. You
want myVariable + 12 to be calculated before the division by myOtherVariable is calculated, so
quite rightly you know you need to put it in parentheses:
(myVariable + 12) / myOtherVariable
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 equality (==)
The equality operator is a commonly confused operator. Consider the following code:
var myNumber = 99;
if (myNumber = 101) {
alert("myNumber is 101");
} else {
alert("myNumber is " + myNumber);
}
At first glance, you'd expect that the code inside the else statement would execute, telling us that
the number in myNumber is 99 . 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 .
What makes things even trickier is that JavaScript does not report this as an error; it's valid
JavaScript! The only indication that something isn't correct is that your code doesn't work.
Assigning a variable a value in an if statement may look like an error, but it's perfectly legal.
When embedded in a large chunk of code, a mistake like this is easily overlooked. Just remember it's
worth checking for this error the next time your program doesn't do what you expect. Debugging your
code can help easily spot this type of error. You learn how to debug your code later in this chapter.
 
Search WWH ::




Custom Search