Read more

JavaScript: How to check if an object is NaN

Arne Hartherz
October 31, 2014Software engineer at makandra GmbH

JavaScript's NaN ("Not a Number") is hard to compare against. It never equals anything, not even itself:

NaN === NaN;        // false
Number.NaN === NaN; // false
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

There is the isNaN method, but it is not really what you are looking for:

isNaN(NaN)     // true
isNaN('hello') // true

Option 1: ES6

The Object.is() method determines whether two values are the same value. It even works for NaN:

Object.is(NaN, NaN) // true

Option 2: ES5

The example above shows that simply using isNaN would match other objects, too. However, look at the weird type of "Not a Number":

typeof NaN // "number"

Hence we can actually check against NaN like this:

var something = NaN;
typeof something === 'number' && isNaN(something) // true

Wow.

Posted by Arne Hartherz to makandra dev (2014-10-31 17:50)