Monday, February 01, 2010

Javascript – a quick and robust check for NotANumber (NAN)

Javascript provides the NaN property that returns a value that represents NotANumber (NAN).
eg: Number.NaN

But you cannot use the following check to test for a variable containing a NaN:
(someValue == Number.NaN)

The reason is because Number.NaN != Number.NaN by definition of the IEEE standards.

This inequality can be used to your advantage by using the following check:
(someValue != someValue)
The only time the above check will fail is that if someValue contains a NaN value.

Or you can use the global function isNaN(someValue).

note: the (someValue != someValue) is a check that works in many other languages (eg: c, c++, SQL, etc) which is why it is a useful idea to brush into the recesses of your memory.

No comments: