2

I tried to check if the input entered by a user is a number or not with the code below. It didn't work.

var a = Number(prompt("Enter a number"));
if (a !== NaN) {
    console.log("yes");
}
else {
    console.log("no");
}

I tried printing the value of a when the input wasn't a number and the output was NaN. But still, this code doesn't work. I know I can use isNaN(), but why doesn't my code work? And is there some other way to check if the input is a number without using isNaN()?

Maaverik
  • 193
  • 2
  • 10
  • 1
    `NaN` is the only value which is not equal to itself, therefore `a !== a` will be true only if a is a `NaN`. More [here](http://stackoverflow.com/a/35455535/989121). – georg Mar 12 '16 at 17:04
  • It works great, thanks – Maaverik Mar 12 '16 at 17:17

5 Answers5

2

try isFinite() method

var a = Number(prompt("Enter a number"));
if (isFinite(a)) {
    console.log("yes");
}
else {
    console.log("no");
}
Pavan Teja
  • 3,192
  • 1
  • 15
  • 22
2

Try to use the typeof operator to test your input value :

if(typeof a ==="number"){ 
   console.log(a+" is a number"); 
}

Here is the documentation : https://msdn.microsoft.com/en-us/library/259s7zc1(v=vs.94).aspx

UPDATE :

Try also to use this answer of an older post : https://stackoverflow.com/a/9716488/2862130

Community
  • 1
  • 1
  • It has been a source of endless frustration to me that `typeof(NaN) === "number"`. It literally stands for "Not a Number"... – cjol Mar 12 '16 at 16:58
  • I read the variable a, so before I check types, I have to manually type-cast it to number. In that case, your code won't work. – Maaverik Mar 12 '16 at 17:06
  • I see, check my update, I hope it will help you (see this: http://stackoverflow.com/a/9716488/2862130) – maximilienAndile Mar 12 '16 at 17:08
2

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.

MDN Documentation

cjol
  • 1,485
  • 11
  • 26
0

I often use

    +a !== +a

since NaN != NaN !!

HBP
  • 15,685
  • 6
  • 28
  • 34
0

As georg pointed out, the easiest way is to use if(a === a) since NaN !== NaN

Maaverik
  • 193
  • 2
  • 10