Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NaN is greater than any number in JavaScript? [duplicate]

Tags:

javascript

Here is an example:

parseInt(50) > parseInt('a');

When executing this on a console, it will return false. My original code looks somewhat like this:

variableB = parseInt(jQuery('some-element').html());
if(parseInt(variableA) > variableB)
     // do something
else
     // do something else

Sometimes the some-element will not be filled and thus return NaN. When this happens, I do want the else block to be executed. I am actually getting what I expect, but I just want to make sure that it indeed is intended to work this way.

like image 603
Marco Aurélio Deleu Avatar asked Sep 21 '25 11:09

Marco Aurélio Deleu


2 Answers

In IEEE 754 arithmethic, the floating-point model used by JavaScript, NaN (or not-a-number) is, by definition, not less than, equal to, or greater than any other number.

Notice that this even applies to two NaNs: if x = NaN and y = NaN, the comparison x === y will return false.

Below I quote the portion of the IEEE 754 Standard (Section 5.11) where this behavior is specified:

Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself.

like image 191
Escualo Avatar answered Sep 23 '25 01:09

Escualo


All comparisons involving NaN will always return false.
NaN is neither less than nor greater than any number.

like image 21
SLaks Avatar answered Sep 23 '25 01:09

SLaks