Javascript testing for NaN: why doesn’t !=”NaN” work?
A couple of weeks ago, I was working on a custom HTML wrapper for Captivate quizzes that would behave one way if a score were already stored for that quiz, and another if the score were non-existent or zero.
So, how best to test for the existence of a score? Usually I test for the existence of a value with
if (typeof foo != "undefined"){do something}
When a quiz is not yet taken, the value of quiz.score is “NaN” (Not-a-Number). It seemed logical to assume that the type of “NaN” is “undefined”.
So I tried:
if (typeof quiz.score !="undefined") {do something}
But this test failed, because it turned out that typeof quiz score always registered as “number” even when the score’s value was “NaN.” That made no sense to me, but I forged ahead anyway and tried to test for the value “NaN” by using
if (score !='NaN'){do something}
But this didn’t work either! It took me a little while to figure out why my attempts to test for NaN weren’t working. This is because NaN is a property of the Javascript Number object, and as such it’s type is “number”.
isNaN() is the function that tests whether something is Not-a-Number, so the correct syntax is:
if(!isNaN(score)){do something}