Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialfrank din
Full Stack JavaScript Techdegree Student 1,381 PointsHow 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.
2 Answers
Martin Sole
82,199 PointsHi
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
Casey Beaver
5,619 PointsCasey Beaver
5,619 Pointslet userUpperLim = prompt("Type an upper limit.");
if ( isNaN( userUpperLim )) { userUpperLim = alert("Please type a proper number."); } else { alert("userUpperLim is good."); }