Java Reference
In-Depth Information
}
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 there are 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 fi nds a
difference, it stops, and the result is false . If, after having checked each letter in turn all the way to the
end, it confi rms 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.
However, string comparison in JavaScript is case sensitive. So “P” is not the same as “p” . Taking the
preceding example, but changing the variable myName to “paul” , you fi nd that the condition is false
and the code inside the if statement does not execute.
var myName =”paul”;
if (myName == “Paul”)
{
alert(“myName is Paul”);
}
The >= , > , <= , and < operators work with strings as well as with numbers, but again it is an alphabetical
comparison. So “A” < “B” is true , because A comes before B in the alphabet. However, JavaScript's case
sensitivity comes into play again. “A” < “B” is true , but “a” < “B” is false . Why? Because uppercase
letters are treated as always coming before lowercase letters. Why is this? Each letter has a code number
in the ASCII and Unicode character sets, and the code numbers for uppercase letters are lower than the
code numbers for lowercase letters. This is something to watch out for when writing your own code.
The simplest way to avoid confusion with different cases is to convert both strings to either uppercase or
lowercase before you compare them. You can do this easily using the toUpperCase() or toLowerCase()
function, which you'll learn about in Chapter 4.
Search WWH ::




Custom Search