JavaScript Number NaN Property Number.NaN property

This tutorial explains the NaN property of JavaScript's Number object. NaN is an acronym that stands for "Not a Number", because this property checks whether a value is numerical or not. You may be familiar with JavaScript's isNaN() function, which precisely checks for numerical values.

Since JavaScript cannot represent any kind of number, some values are (counter-intuitively) non-numerical.

isNaN() returns true with imaginary numbers (like square and even roots of negative numbers).

The NaN Property as JavaScript Returned Value

You cannot not equate (with equality or identity operator) the NaN property of JavaScript's Number object with an NaN returned as value from an "illegal operation." This script attempts to extract the root of a negative number:

// Extract a square root with the Math.sqrt() method:
alert( Math.sqrt(-5).toString() );

Since JavaScript cannot handle this result, it returns an indication of problem (and not an unhandled error, as one might expect.) JavaScript Number NaN property

The NaN Property and JavaScript's isNaN() Function

Since the NaN property cannot be equated to anything else (even itself), only the isNaN() function can check for unexpected numerical results. As illustration, the code below returns false on both counts.

// Identity operator
alert( Number.NaN === Number.NaN );

// Equality operator
alert( Number.NaN  == Number.NaN );

In both cases, the result was false: as far as the JavaScript interpreter is concerned, Number.NaN is neither identical nor equal to itself: JavaScript's Number.Nan property

Using the derived isNaN() function, however, we obtain expected results:

// The isNaN() function returns true
alert( isNaN(Number.NaN) );

// Once more, isNaN() returns true
alert( isNaN(Math.sqrt(-5)) );

We omitted toString() for clarity. In both cases, JavaScript returned true; in testing for NaN values, you should use the isNaN() function.

Test the Number NaN Property

Interactively test the Number NaN property by editing the JavaScript code below and clicking the Test Number NaN Property button.

Browser support for JavaScript Number NaN property
Internet Explorer supports the JavaScript Number NaN propertyFirefox supports the JavaScript Number NaN propertySafari supports the JavaScript Number NaN propertyOpera supports the JavaScript Number NaN property