Maaverik
Maaverik

Reputation: 193

Check if input is number in JavaScript by comparing with NaN without using isNaN()

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()?

Upvotes: 2

Views: 333

Answers (5)

Maaverik
Maaverik

Reputation: 193

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

Upvotes: 0

maximilienAndile
maximilienAndile

Reputation: 202

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

Upvotes: 2

cjol
cjol

Reputation: 1495

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

Upvotes: 2

HBP
HBP

Reputation: 16033

I often use

    +a !== +a

since NaN != NaN !!

Upvotes: 0

Pavan Teja
Pavan Teja

Reputation: 3202

try isFinite() method

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

Upvotes: 2

Related Questions