5
>
5
;
// false
5
>=
5
;
// true
5
<
5
;
// false
5
<=
5
;
// true
Comparing Numbers
When doing identity or equality comparisons on numbers, you must take special
care.
First, note that the special numeric value
NaN
is not equal to anything, including itself
(that is,
NaN === NaN
and
NaN == NaN
are both
false
). If you want to test to see if a
number is
NaN
, use the built-in
isNaN
function:
isNaN(x)
will return
true
if
x
is
NaN
and
false
otherwise.
Recall that all numbers in JavaScript are doubles: because doubles are (by necessity)
approximations, you can run into nasty surprises when comparing them.
If you’re comparing integers (between
Number.MIN_SAFE_INTEGER
and
Number.MAX_SAFE_INTEGER
, inclusive), you can safely use identity to test for equality.
If you’re using fractional numbers, you are better off using a relational operator to see
if your test number is “close enough” to the target number. What’s close enough? That
depends on your application. JavaScript does make a special numeric constant avail‐
able,
Number.EPSILON
. It’s a very small value (about
2.22e-16
), and generally repre‐
sents the difference required for two numbers to be considered distinct. Consider this
example:
let
n
=
0
;
while
(
true
) {
n
+=
0.1
;
if
(
n
===
0.3
)
break
;
}
console.log(
`Stopped at
${
n
}
`
);
If you try to run this program, you will be in for a rude surprise: instead of stopping
at 0.3, this loop will skip right past it and execute forever. This is because 0.1 is a well-
known value that can’t be expressed exactly as a double, as it falls between two binary
fraction representations. So the third pass through this loop,
n
will have the value
0.30000000000000004
, the test will be
false
, and the only chance to break the loop
will have passed.
You can rewrite this loop to use
Number.EPSILON
and a relational operator to make
this comparison “softer” and successfully halt the loop:
Comparing Numbers | 87