Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

NaN and Infinity in JavaScript

[2012-02-13] numbers, dev, javascript, jslang
(Ad, please don’t block)

Update: New section “Detecting NaN”.

This post looks at two special values that can be the result of operations that normally return numbers: NaN and Infinity.


The value NaN in JavaScript stands for “not a number”. It mainly indicates that parsing a string has gone wrong:
    > Number("xyz")
NaN has some Koan-like qualities. Its name is “not a number”, but it’s also not not a number (triggered by a tweet by Ariya Hidayat):
    > NaN !== NaN
Yet, its type is “number”.
    > typeof NaN

Detecting NaN

NaN is the only JavaScript value that is not equal to itself. Without equality at your disposal, you have to use the global function isNaN() to detect it.
    > isNaN(NaN)
Kit Cambridge (via Mathias Bynens) points out a pitfall of isNaN(): It coerces its argument to number and will thus even return true for strings that cannot be converted to numbers:
    > Number("xyz")
    > isNaN("xyz")
For the same reason, isNaN will also return true for many objects:
    > Number({})
    > isNaN({})

    > Number(["xzy"])
    > isNaN(["xzy"])
Consult [1] for details on the conversion algorithm. It is possible to override valueOf to control the result of the conversion to number:
    > var obj = { valueOf: function () { return NaN } };
    > Number(obj)
    > isNaN(obj)
Cambridge’s suggested work-around is to exploit the fact that NaN is the only value x that is non-reflexive (x !== x):
    function myIsNaN(x) {
        return x !== x;
A fixed version of isNaN will probably be added to ECMAScript 6 as Number.isNaN(). Crockford’s specification of that function better reveals what one is trying to do than Cambridge’s version. It looks as follows (simplified for explanatory purposes):
    Number.isNaN = function (value) {
        return typeof value === 'number' && isNaN(value);


Division by 0 gives you another special value:
    > 3/0
You can’t play positive and negative infinity against each other:
    > Infinity - Infinity
It also turns out that “beyond infinity” is still infinity:
    > Infinity + Infinity

    > 5 * Infinity


  1. What is {} + {} in JavaScript?