4

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.

4
  • 1
    if(parseInt(variableA) > variableB && !isNaN(variableB)) Commented Nov 17, 2014 at 22:08
  • 2
    You didn't test the reverse, did you? The comparison, whether >, < or === is false; NaN is neither greater-than, less-than or equal to any number. And, dammit, next time I answer instead of commenting... >.< Commented Nov 17, 2014 at 22:08
  • why not check for variableB to see if it is a NaN before continuing? Commented Nov 17, 2014 at 22:08
  • I hadn't tested the reverse David, thanks for pointing that out. Commented Nov 17, 2014 at 22:11

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

2 Comments

Strictly speaking, though, that's not entirely true, is it; or does !==/!= not count as a 'comparison'? (I'm perhaps being pedantic, but I don't know if I'm missing a technicality in your statement or not.)
@DavidThomas The interpreter probably does the negation separately to the comparison. That is, it first checks if NaN == NaN or NaN === NaN (false) then negates (true). There's no non-equality operator, just an equality operator and a syntactic sugar for negating it. 8 years later is probably better than never.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.