Skip to content

Comment on Speaking JavaScript

Comments

I never knew that NaN is not strictly equal to itself in JavaScript (so NaN === NaN => false). Very interesting.

The reason is simple:

"hello" is Not a Number. "world" is Not a Number.

(Number)"hello" == (Number)"world" returns false.

EDIT: Another reason why this is the case is because IEEE mandates it to be. All numbers in JS are 64 bit floating point numbers. This allows for a crazy amount of NaNs (and oh the fun stuff you can do with that). To be sane, NaNs are not the same when comparing them (there is a lot more subtlety in that - comparing quiet and signalling NaNs, and so on and so forth)

It makes sense. Just because both things are not something does not mean they are the same.

I would be surprised if it were. All languages I know says NaN == NaN is false.

It's actually part of some cryptic and ancient standard and is common for nearly all languages nowadays. I never cared about it very much, but here's the post on NaN semantics from someone who apparently designed the standard:

http://stackoverflow.com/questions/1565164/what-is-the-ratio...

cryptic and ancient standard

Cryptic and ancient?! IEEE 754 is the behavior implemented by the chip in the computer you're using to browser HN with right now.

"In current and common use" is not actually the opposite of "cryptic and ancient".

I get your point, but....

Ancient it is not, and old isn't bad. Lots of deep thinking went into IEEE-754, http://www.cs.berkeley.edu/~wkahan/ieee754status/754story.ht... calculating with computers is hard work.

This reminds me of a hilarious Destroy All Software screencast about oddities in certain programming languages: https://www.destroyallsoftware.com/talks/wat

That's the canonical way to check for NaN, in fact.

No. Use isNaN() instead. Or if you have ES6 support, Number.isNaN() is much better an implementation than window.isNaN()

This makes it easy to test for NaN! It's the only value for which this is true. (And the built-in isNaN() function has misleading behavior.)

if a !== a then a is NaN

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.