0

I created a simple prompt that allows a user to input a number between 1 and 10. First I change answer from a string into a number. Second I check to see if answer is between 1 and 10 or is NaN. If answer is outside 1 and 10 or NaN the loop runs and checks again. while correctly detects if numbers are less than 1 or greater than 10 however it doesn't properly detect if answer == NaN. I'm not sure why it doesn't work with letters because the alert indicates that answer does = NaN when I input letters. Can anybody see what I'm doing wrong?

var answer;
 
do {
    answer = prompt("Enter a number between 1 and 10.");
    answer = Number(answer);
}
while (answer < 1 || answer > 10 || answer == NaN);
 
alert(answer);
DR01D
  • 1,325
  • 15
  • 32

2 Answers2

3

For detecting if answer is NaN, you can use the isNaN() function.

Update

As far as browser support, Number.isNaN() is supported on all major browsers with the exception of Internet Explorer. The global isNaN() function is supported on IE.

M3talM0nk3y
  • 1,382
  • 14
  • 22
1

In general, (although it doesn't make a difference here) it's better to use Number.isNan over isNaN. Hence, for best results try this:

var _isNaN = Number.isNaN || isNaN;
var answer;

do {
    answer = prompt("Enter a number between 1 and 10.");
    answer = parseInt(answer, 10);
} while (answer < 1 || answer > 10 || _isNaN(answer));

alert(answer);

Also, note that using parseInt is better than using the Number constructor.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • 1
    If you're targeting a Microsoft Browser, the [Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) is only supported in ***Edge***, and not in ***Internet Explorer***. – M3talM0nk3y Aug 19 '17 at 02:43
  • Which is why we have the default set as `isNaN`. Also, please stop screaming. – Aadit M Shah Aug 19 '17 at 02:44
  • 1
    Screaming means the usage of all CAPS; bold text is a mean for emphasizing a remark or comment... Don't be too sensitive. – M3talM0nk3y Aug 19 '17 at 02:53