↑
Main Page
Equality operators
var bResult = “23” < 3;
alert(bResult); //outputs “false”
Here, the string
“23”
is converted into the number
23
and then compared to
3
, giving the expected
result. Whenever a number is compared to a string, ECMAScript says that the string should be con-
verted into a number and then numerically compared with the other number. This works well for
cases like the previous example, but what if the string can’t be converted into a number? Consider this
example:
var bResult = “a” < 3;
alert(bResult);
What would you expect this to output? The letter
“a”
can’t be meaningfully converted into a number.
After all, if you were to use
parseInt()
on it,
NaN
would be returned. As a rule, any relational opera-
tion that contains
NaN
returns
false
, so this code also outputs
false
:
var bResult = “a” >= 3;
alert(bResult);
Typically, if two values return
false
for a less-than operation, they must return
true
for a greater-than-
or-equal operation, but this is not the case when one number is
NaN
.
Equality operators
Determining whether two variables are equivalent is one of the most important operations in program-
ming. This is fairly straightforward when dealing with primitive values, but the task gets a little compli-
cated when you take objects into account. To deal with this problem, ECMAScript provides two sets of
operators: equal and not equal to deal with primitive values, and identically equal and not identically
equal to deal with objects.
Equal and not equal
The equal operator in ECMAScript is the double equal sign (
==
), and it returns
true
if — and only if —
both operands are equal. The not equal operator is the exclamation point followed by an equal sign (
!=
),
and it returns
true
if — and only if — two operands are not equal. Both operators do conversions in
order to determine if two operands are equal.
When performing conversions, follow these basic rules:
?
If an operand is a Boolean value, convert it into a numeric value before checking for equality.
A value of
false
converts to 0; whereas a value of
true
converts to 1.
?
If one operand is a string and the other is a number, attempt to convert the string into a number
before checking for equality.
?
If one operand is an object and the other is a string, attempt to convert the object to a string
(using the
toString()
method) before checking for equality.
?
If one operand is an object and the other is a number, attempt to convert the object to a number
before checking for equality.
50
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 50
Free JavaScript Editor
Ajax Editor
©
→ R7