Checking NaN Values

NaN is a global property that represents an IEEE 754 “not a number”. (There is also a static NaN property of the built-in Number object, Number.NaN for pointless duplication (mdn)).

In older versions of ECMAScript NaN and other global properties like undefined were writable. You shouldn’t be doing that and Brendan, et al made it illegal; even throwin errors in strict mode..

The value type of NaN is “number”, as can be seen by the literal NaN property or by NaN values.

typeof NaN; // "number"
typeof (1 / "foo"); // "number"

Any value compared to NaN using the comparison operators == or === results false.

NaN == NaN; // false
undefined == NaN; // false

Method isNaN almost seems to work:—

isNaN(NaN); // true

— until it does type conversion, even attempting to run the algorithm when no argument is supplied.

isNaN(); // true
isNaN(undefined); // true
isNaN("-."); // true
isNaN(""); // false
isNaN("-2."); // false

The answer to that is to use Number.isNaN, which only returns true for actual NaN values and does not do type conversion.

Number.isNaN(); // false
Number.isNaN("1"); // false
Number.isNaN(""); // false
Number.isNaN("-."); // false
Number.isNaN("0xf"); // false
Number.isNaN("-2."); // false

Object.is can also reliably check NaN values:

 Object.is(NaN, NaN); // true
 Object.is(NaN, undefined); // false

Methods isFinite and the newer non-type-converting version Number.isFinite can work in certain situations:—

 Number.isFinite(NaN); // false

— but do not check exclusively for NaN, as they also return true for Infinity and -Infinity:—

 Number.isFinite(-Infinity); // false

But these methods are useful for numeric validation. Especially Number.isFinite, which, unlike global isFinite, does not do type conversion:

Number.isFinite("2"); // false
Number.isFinite(new Date); // false
isFinite("2"); // true
isFinite(new Date); // true

Leave a Reply

Your email address will not be published. Required fields are marked *