How does 'parseInt("") != NaN' evaluate to true?

I’ve tried this in the console, and it doesn’t make sense.

parseInt("") evaluates to NaN. A falsy value

So why does parseInt("") != NaN evaluate to true?

NaN != NaN also evaluates to true

For the record, the same happens when you use the strict comparison, ===

And NaN == NaN evaluates to false

My brain hurts

NaN === NaN
// false

isNaN(NaN)
// true

parseInt('')
// NaN

isNaN(parseInt(''))
// true
1 Like

NaN compares unequal (via == , != , === , and !== ) to any other value – including to another NaN value.

Thanks. I hate it

Nah, but it is rather interesting. Gonna have to look into why this decision was made. Surely there’s a reason

1 Like

I’m just spitballing here, but NaN is basically not a value itself, more of an error state. Personally, I would much prefer that parseInt throw an error that I need to handle rather than become a useless “value” (that you should handle anyway, it’s just less explicit).

But if NaN were equal to itself then this kind of weird stuff could happen:

const userInput = "foo"
const otherUserInput = "bar"

if (parseInt(userInput) === parseInt(otherUserInput)) {
  // do something unexpected if NaN equals NaN
}
2 Likes

Yup. You really, really never want to say that two NaNs are equal since there is a huge number of ways to make a NaN. Your code starts to do surprising stuff if that is all.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.