0

I have written below code in JS.

function foo() {

var s = "Jack";
s = parseInt(s);
console.log(s)
if (s!=NaN) {
    if (typeof (s) == "number")
        console.log("number");
    else if (typeof (s) == "string")
        console.log("string");
} else {
    console.log("Your entry is not a number");
}

}

As i am trying to parseInt a string, i got NaN as value.

We know that typeof(NaN) is "number" and numbers can be compared directly like(1==1) in IF condition. But this didn't work.

I tried with isNaN(s) and it worked where as s!=NaN failed.

why ?

vinod
  • 830
  • 8
  • 14

1 Answers1

1

The necessity of an isNaN function

Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.[Ref]

Conclusion: NaNis never equals to anything including NaN itself hence rely on Number.isNaN(value) method.

console.log(NaN == NaN);
console.log(NaN === NaN);
console.log(NaN === undefined);
console.log(NaN === null);
console.log(NaN === 'TEST');
console.log(NaN === 0);
Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • That's what the OP did. The question is not how to test for NaN by why the equality operator doesn't work: *"I tried with isNaN(s) and it worked where as s!=NaN failed. Why?"* – Felix Kling Jun 23 '16 at 07:00
  • http://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values – Pradeep Kr Kaushal Jun 23 '16 at 07:04