Reputation: 21842
While working in my JS code today, I found the following situation and can not explain myself what should be the correct output ?
'sachin' > 2 // False
'sachin' < 2 // False
'sachin' == 2 // False
I expect result of either of <
or >
should be true. What am I missing ?
Upvotes: 2
Views: 3465
Reputation: 413826
When the runtime attempts to convert 'sachin'
to a number, it will fail and end up as NaN
. That special constant results in false
for any comparison to any other numeric value. The NaN
constant ("Not A Number") is not equal to any other value, nor is it less than or greater than any other value.
edit — the ==
, <
, and >
operators all "prefer" numbers to strings. If one operand is a number and the other a string, they'll always try to interpret the string as a number. It doesn't matter what order the operands appear in; what matters is the operand types.
(Strictly speaking, the results of <
and >
when NaN
is involved are supposed to be undefined
, according to the spec, but Firefox seems to give false
instead.)
Upvotes: 4