Java Reference
In-Depth Information
doesn't belong to the right if . This is quite tricky to describe with words—it's easier to see what we
mean with an example:
if (myAge >= 0 && myAge <= 10) {
document.write("myAge is between 0 and 10");
if (myAge == 5){
document.write("You're 5 years old");
}
}else{
document.write("myAge is NOT between 0 and 10");
}
Notice that we haven't indented the code. Although this does not matter to JavaScript, it does make
the code more difficult for humans to read and hides the missing curly brace that should be before
the final else statement.
Correctly formatted and with the missing bracket inserted, the code looks like this:
if (myAge >= 0 && myAge <= 10) {
document.write("myAge is between 0 and 10<br />");
if (myAge == 5) {
document.write("You're 5 years old");
}
} else {
document.write("myAge is NOT between 0 and 10");
}
As you can see, the code is working now; it is also a lot easier to see which code is part of which if
block.
Comparing strings
Up to this point, you have been looking exclusively at using comparison operators with numbers.
However, they work just as well with strings. All that's been said and done with numbers applies to
strings, but with one important difference. You are now comparing data alphabetically rather than
numerically, so you have a few traps to watch out for.
In the following code, you compare the variable myName , which contains the string "Paul" , with the
string literal "Paul" :
var myName = "Paul";
if (myName == "Paul") {
alert("myName is Paul");
}
How does JavaScript deal with this? Well, it goes through each letter in turn on the LHS and checks
it with the letter in the same position on the RHS to see if it's actually the same. If at any point it
finds a difference, it stops, and the result is false . If, after having checked each letter in turn all
the way to the end, it confirms that they are all the same, it returns true . The condition in the
preceding if statement will return true , so you'll see an alert box.
 
Search WWH ::




Custom Search