rummykhan rummykhan - 3 months ago 14
Javascript Question

Why parseInt(key) === NaN always evaluates to false

I'm doing decision based on dictionary key, i have only two types of keys, numeric and alpha,

var _dict = { 'a':'one', 'b':'two', '1':'three' };

$.each( _dict, function( key, value ){

if( parseInt( key ) === NaN ) {

// this statement always evalute to false

} else {

}

});


if i print
console.log(parseInt('a'))
, it will also return
NaN


I alreay found the solution from this question javascript parseInt return NaN for empty string

But i was wondering why it always evaluates to false.

Answer

That's because NaN is defined to be not equal to anything (including itself). Check it:

>> NaN === NaN
False

You should use isNaN() function instead:

>> isNaN(NaN)
true
>> isNaN(0/0)
true
>> isNaN(parseInt('a'))
true