What is NaN in JavaScript

If you try to convert something to number and it can’t be done, you get a special value NaN.

For instance,

function doubleMe(x) {
if (typeof x !== 'number') {
x = Number(x);
}
return 2 * x;
}

JavaScript implicitly convert types on demand, so it could be just:

function doubleMe(x) {
// if x is not a number,
// it’d be converted under the hood
return 2 * x;
}

What if x equals ‘foo’? Obviously, it makes no sense as a number, so result of conversion and multiplication would be NaN (not a number).

NaN is just a special value to return as a result of conversion to number instead of throwing an exception, if type conversion has failed.

It has some weird properties:

  • there’s no special primitive type for NaN, it’s a number 😃
  • NaN doesn’t equal to any other value including itself

The last fact provides a way to check if the value is NaN.

function isNaN(value) {
return value !== value;
}

So, there’s a simple ES6 polyfill:


if (!Number.isNaN) {
Number.isNaN = function(value) {
return value !== value;
}
}