Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (1 < NaN) false in JavaScript?

Tags:

Why does (1 < NaN) give back false and not undefined (in JavaScript)?

In "11.8.5 The Abstract Relational Comparison Algorithm" it says that if either of the values is NaN (after ToPrimitive and ToNumber which should not affect NaN in my view) the result is undefined.

In FF and Chrome I get:

console.log(1 < NaN);
// false

Why is that?

like image 936
Sacha Avatar asked Jul 13 '11 09:07

Sacha


People also ask

Is NaN false in JavaScript?

There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.

Why does NaN NaN give false?

Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.

Is NaN always false?

This means that in JavaScript, isNaN(x) == true is equivalent to x - 0 returning NaN (though in JavaScript x - 0 == NaN always returns false, so you can't test for it). Actually, isNaN(x) , isNaN(x - 0) , isNaN(Number(x)) , Number.

Is NaN true in JavaScript?

isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.


1 Answers

Because the < operator returns false when the abstract relational algorithm returns undefined. See Section 11.8.1:

11.8.1 The Less-than Operator ( < )

The production RelationalExpression : RelationalExpression < ShiftExpression is evaluated as follows:

  1. Let lref be the result of evaluating RelationalExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating ShiftExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of performing abstract relational comparison lval < rval. (see 11.8.5)
  6. If r is undefined, return false. Otherwise, return r.

This is true of all of the relational operators. The algorithm has an undefined outcome, but the operators convert that to false. And that makes sense. 1 isn't < NaN (nor is it > NaN, or == NaN, or... :-) ).

(Nice to see people reading the spec.)

like image 172
T.J. Crowder Avatar answered Sep 22 '22 14:09

T.J. Crowder