Tag Archives: javascript

Handling NaN values

Javascript provides a function called parseInt that, well, parses texts as integers. So parseInt("5") returns 5. Great. However parseInt("hi") returns NaN, Not a Number, it makes sense.

Lately I wanted to assign a variable the value returned by parseInt or a default value if the function returns NaN. I found this solution:

var variable = parseInt(x) || 0;

Which assigns 0 as a default value if parseInt returns NaN. Perfect. Then I wanted to assign 1 as a default value:

var variable = parseInt(x) || 1;

If x = “3”, 3 was assigned. On the other hand, if x=”hi”, 1 was assigned. But what about x=”0″?

1. Just 1. One. No 0. 1.

I imagine that 0 is being interpreted as boolean false, so the default value is assigned.

So don’t ever use this solution. Use function isNaN to check the result given by parseInt instead.

By the way, NaN != NaN. Wat.