DEV Community

Discussion on: What is the type of NaN?

Collapse
 
val_baca profile image
Valentin Baca • Edited

c/o "You Don't Know JS"

github.com/getify/You-Dont-Know-JS...

NaN isn't equal to itself. NaN is the only value in the whole language where that's true; every other value is always equal to itself.

So:

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

Weird, huh? But it works!

Despite the (condescending) name, the YDKJS series is actually really great.

Collapse
 
vicoerv profile image
Vico

did the interpreter work like this.

if (token[0] == 'NaN') return false;

return token[0] == token[1];

just kidding

Collapse
 
clarity89 profile image
Alex K. • Edited

Haha, well it's more like each NaN has a different value under the hood, so technically they're not equal to each other.

Fun fact: since most of the bits in NaN encoding aren't used to store any meaningful information, they can be manipulated to store actual data - payload. This is called NaN-tagging or NaN-boxing and is mostly used for adding additional type encodings to values. Here's one interesting article about it.

Thread Thread
 
vicoerv profile image
Vico

wow thank you, never thought about that