SidekickJS's blog

NaN !== NaN: you wouldn't want it any other way

NaN !== NaN for a good reason. It’s funny it’s considered a ‘bad part’ in lots of ‘Javascript sucks lol’ posts as it’s exactly the same in Java, Python and .NET.

NaN is the placeholder answer to questions that are not mathematically sensible . Just like there’s no sensible answer to “what is the weight of the verb ‘laugh’?”, there are numerical questions we can’t give a good answer to:

Number(undefined) // NaN
0 / 0 // NaN
Math.log(-1) // NaN
Math.acos(2) // NaN
parseInt("I hate maths, can we just use words?") // NaN

Since NaN is given as the same “that’s a dumb question” answer to all dumb questions, if it were equal to itself we’d get some strange behaviour. Would anyone prefer the following equality tests to pass?

Math.log(-1) === parseInt("oh want a number? one")
0 / 0 === Math.acos(2)

Commonly, the next thing after bemoaning this ‘problem’ is to question how we can identify NaN values if we NaN !== NaN. Well: Javascript has contained the global isNaN() function from version one.

isNaN() can be tricky thanks to implicit coercion on being passed strings or literals. However, when using isNaN() that’s usually fine as you’re expecting a numeric. If you’ve somehow got code that could either be a string or a number (yuk) you can shim it with function isNaN(x) { return x !== x }, or wait for the ES6 version.

It’s valid to argue that throwing an exception would be a neater and more helpful alternative: e.g Ruby throws the exception Numerical argument is out of domain for log(-1). This makes it clear what’s gone wrong, and will stop execution rather than letting NaN be passed around. However, NaN is specified by the standard JS uses for floating point arithmetic and therefore ‘NaN’ is consistently used instead of exceptions in numerical operations.

Javascript has flaws, but the ‘WAT’ meme has lead to some innocent ‘good parts’ being speciously condemned along with them.