JavaScript JavaScript Numbers The Math Object Random Number Challenge – Solution

How do you determine if a value is not a number?

I'm trying to add an error message in case the user typed a value that was not a number, but I can't find a way to detect if a value is a number or not? const userUpperLim = +prompt(Type an upper limit); if (userUpperLim === NaN){ alert(please type proper number); } else{ alert(userUpperLim is good); }

I tried this but it skips right over the if statement and goes to the else statement.

Casey Beaver
Casey Beaver
4,915 Points

let userUpperLim = prompt("Type an upper limit.");

if ( isNaN( userUpperLim )) { userUpperLim = alert("Please type a proper number."); } else { alert("userUpperLim is good."); }

2 Answers

Martin Sole
Martin Sole
80,279 Points

Hi

You can also use typeof which checks a values type. So for your example it could be used as

if (typeof userUpperLim !== 'number')

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

furkan
furkan
10,278 Points

Hey there,

Have a look at this link, might help:

https://www.w3schools.com/jsref/jsref_isnan.asp