↑
Main Page
Relational operators
?
If
Infinity
is subtracted from
Infinity
, the result is
NaN
.
?
If –
Infinity
is subtracted from –
Infinity
, the result is
NaN
.
?
If –
Infinity
is subtracted from
Infinity
, the result is
Infinity
.
?
If
Infinity
is subtracted from –
Infinity
, the result is –
Infinity
.
?
If +0 is subtracted from +0, the result is +0.
?
If –0 is subtracted from +0, the result is –0.
?
If –0 is subtracted from –0, the result is +0.
?
If either of the two operands is not a number, the result is
NaN
.
Relational operators
The less-than (
<
), greater-than (
>
), less-than-or-equal (
<=
), and greater-than-or-equal (
>=
) relational oper-
ators perform comparisons between numbers in the same way that you learned in math class. Each of
these operators returns a Boolean value:
var bResult1 = 5 > 3; //true
var bResult2 = 5 < 3; //false
When a relational operator is used on two strings, however, a different behavior occurs. Many expect
that less-than means “alphabetically before” and greater-than means “alphabetically after,” but this is
not the case. For strings, each of the first string’s character codes is numerically compared against the
character codes in a corresponding location in the second string. After this comparison is complete, a
Boolean value is returned. The problem here is that the character codes of uppercase letters are all lower
than the character codes of lowercase letters, meaning that you can run into situations like this:
var bResult = “Brick” < “alphabet”;
alert(bResult); //outputs “true”
In this example, the string
“Brick”
is considered to be less than the string
“alphabet”
because the let-
ter
B
has a character code of 66 and letter
a
has a character code of 97. To force a true alphabetic result,
you must convert both operands into a common case (upper or lower) and then compare:
var bResult = “Brick”.toLowerCase() < “alphabet”.toLowerCase();
alert(bResult); //outputs “false”
Converting both operands to lowercase ensures that
“alphabet”
is correct identified as alphabetically
before
“Brick”
.
Another sticky situation occurs when comparing numbers that are strings, for example:
var bResult = “23” < “3”;
alert(bResult); //outputs “true”
This code will output
“true”
when comparing the string
“23”
to
“3”
. Because both operands are
strings, they are compared by their character codes (the character code for
“2”
is 50; the character code
for
“3”
is 51). If, however, one of the operands is changed to a number, the result makes more sense:
49
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 49
Free JavaScript Editor
Ajax Editor
©
→ R7