Daniel Escobedo

Testing for NaN in ES6

Testing for NaN in ES6

Reliably testing for NaN has become much simpler (and safer) in ES6 using Number.isNaN( x ):

a = "foo" * 2;
b = "bar";

Number.isNaN( a );  // true
Number.isNaN( b );  // false

How is this different than the current isNaN( x )?

We are trying to test for, and find the value NaN. isNaN( x ) doesn’t check if the value is NaN; It checks to see if the value is literally not a number:

a = "foo" * 2;
b = "bar";

isNaN( a );  // true
isNaN( b );  // true

While it is true that b is not a number (string), we want to check to see if b is the value NaN not check if it was literally a number. If you are using isNaN( x ) to test against NaN, you are explicitly creating a bug in your application and need to avoid it.

Polyfill pre-ES6

A very simple way to write this polyfill is by understanding that NaN is a very special kind of value in JavaScript, in which NaN is never equal to itself:

NaN !== NaN  // true

While this is rather odd, this helps us write the simplest polyfill ever:

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

Daniel Escobedo

I'm a JavaScript developer who loves to code. I'm always reading and learning new technologies and tools to better my skills and workflow.

View Comments
Next Post

React Component Lifecycle Methods

Previous Post

JavaScript Equality Test with Machine Epsilon in ES6