Posted by podlipensky on October 20 11:10 AM

 

One thing I always amusing with Javascript is NaN. Arguably, NaN is a bit quirky in most languages, but it really interesting in Javascript. (For those of you that don’t know, NaN stands for “not a number”). Consider:

typeof NaN === 'number'; // true 
NaN === NaN; // false 
NaN !== NaN; // true
NaN + 1; //NaN
1 < NaN; //false

There are four kinds of operation which return NaN:

  • Operations with a NaN as at least one operand
  • Indeterminate forms

The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞ 
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.

  • Real operations with complex results:

The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than -1 or greater than +1.

  • Invalid Number constructor or invalid number string during parsing operation

For example,

Math.sqrt(-4); // NaN
Number("foo"); //NaN 
parseInt("bar"); //NaN

As for me the most illogical here is NaN comparsion

NaN === NaN; // false
1 < NaN; //false

And recently I found an explanation of such strange behavior (from spec Section 11.8.1):

11.8.1 The Less-than Operator ( < )

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

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

This is true of all of the relational operators. The algorithm has an undefined outcome (NaN converted to undefined), but the operators convert that to false. And that makes sense.

blog comments powered by Disqus