1

I want to ask the user for a number, while his answer is not a number the question will keep on looping (as an alert box).

I tried to do that with while loop and isNaN, but i'm doing something wrong.

Here is my Js:

var correct = false;

do {
    var question = prompt("guess the number?");
    if (question !== isNaN) {
        document.write("your number is " + question);
        correct = true;
        break;
   }

} while(! correct);
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
CodeChunk
  • 83
  • 2
  • 11

6 Answers6

2

A couple of mistakes

  • isNaN() is a function: isNaN(NaN) returns true while isNaN(1) or isNaN("1") returns false
  • prompt() always returns a string (never NaN)

You can convert the result from prompt() to a number using the unary + operator, then check if it is NaN;

var question = prompt("guess the number?");
if (!isNaN(+question)) {
  ...

That said, isNaN() is a bad fit if you're simply trying to see if a string contains only numbers, since whitespace ("" or " " or "\n\t") will all convert to 0and give you false positives.

A simple regex will do the right thing;

var question = prompt("guess the number?");
var containsOnlyDigits = /^[0-9]+$/; // one or more of digits 0 to 9
if (containsOnlyDigits.test(question)) {
  ...
Community
  • 1
  • 1
xec
  • 17,349
  • 3
  • 46
  • 54
2

I will give you some tips with the following sample:

<html>
 <head>
    <title></title>
    <script>

    var answer = "";

    do {
        answer = prompt("guess the number?");
    } while(!isNumber(answer));

    document.write("your number is " + answer);

    function isNumber(value) {
      var numberPattern = /^[0-9]+$/; // one or more of digits 0 to 9
      return numberPattern.test(value);
    }

    </script>
 </head>
 <body>

</body>

Example here: https://plnkr.co/edit/ziysG36if9OTZahHfSbO

  • It is not necessary to create an additional variable called correct to check if the condition is true or false because you have the condition clear, isNan(answer), so the while should use that condition "while (isNan(answer))".

  • When you write code you should write as clean as possible and if you are saving the result of prompt it is more clear to name the variable "answer" because you are saving the answer and not the question, which is a method call.

Alejandro Morán
  • 669
  • 1
  • 13
  • 36
  • thanks! can you explain why did you declare the var answer outside the loop and called it again inside? instead of declaring the variable inside the loop? thx – CodeChunk Apr 11 '16 at 15:34
  • @xec The loop is expected to run once if the answer is a number as he wrote in his question "while his answer is not a number the question will keep on looping (as an alert box).". – Alejandro Morán Apr 11 '16 at 15:35
  • @CodeChunk edited, it's unnecessary to declare it outside of it's scope, which is actually the while loop – Alejandro Morán Apr 11 '16 at 15:37
  • can you explain it more detailed about declaring a variable outside of the loop or inside? – CodeChunk Apr 11 '16 at 15:42
  • @CodeChunk For this example doesn't make much difference, in other languages you can't access variables out of their strict scope, which means you should not be able to access "answer" out of the while if it is delcared inside, but is not applicable now. – Alejandro Morán Apr 11 '16 at 15:47
  • @xec I do get isNan(answer) equals to true even if it is a string, shouldn't I ¿? (using Chrome) --> console.log(isNaN("a")); -> true console.log(isNaN("1")); -> false console.log(isNaN(1)); -> false console.log(isNaN('1')); -> false – Alejandro Morán Apr 11 '16 at 15:48
  • @xec Both solutions mine and yours have a little mistake, if the user prompts an empty string or whitespaces the isNaN() function returns false because it manages that strings as zero value, so our solution can be more efficient. – Alejandro Morán Apr 12 '16 at 13:53
  • @AlejandroMorán That's a good point. Updated my answer, using a regex instead is much better. – xec Apr 13 '16 at 08:19
  • @xec Really cool, I've also updated mine with your approach, that's a good way to achieve this goal, there's more ways to do it here: http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers – Alejandro Morán Apr 13 '16 at 08:50
1

isNan is a function - you need to call it by putting parentheses after it, and then putting your arguments inside those parentheses.

The isNaN function returns true if the argument isn't a number, and false if it is. Since you want to check if question is a number, we can then invert the boolean output using the ! prefix, which will cause the if statement's body to trigger if question is a number.

var correct = false;

do {
  var question = prompt("guess the number?");
  if (!isNaN(question)) {
    document.write("your number is " + question);
    correct = true;
    break;
  }
} while (!correct);
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
1

isNaN is a function with some special rules. You should first try to parse the input to a number and then use isNaN on that result. Number returns NaN, if the conversion from a string to number failed.

var input1 = "1234";
var input2 = "abcd";

alert(isNaN(Number(input1)));
alert(isNaN(Number(input2)));
hansmaad
  • 18,417
  • 9
  • 53
  • 94
1

As mentioned above - isNan is a function which gets a parameter as its input.

You don't have to convert the prompt to a number before the test in isNan as you can see in the documentation it can accept strings as well.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Examples

The function will do the conversion internally behind the scenes:

You could think of isNaN as:

isNaN = function(value) {
   Number.isNaN(Number(value));
}

Here is a code snippet which will work for you:

var correct = false;

do {
    var answer = prompt("guess the number?");

    // The isNaN function gets an number argument
    // You also need to check if there is value.
    // If the user click no ESC you will get null
    if (answer && !isNaN(answer)) {

        // You cant write to the document once its loaded.
        // it will clear any previous content in the page
        document.write("your number is " + answer);
        correct = true;
        break;
    }

} while (!correct);
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
0

Here is a similar solution:

for (let numTrue = false; !numTrue;) {
 var question = prompt("Guess the Number!", "Number");
 numTrue = !isNaN(question);
}
document.write("Your number is " + question);
Michael Kargl
  • 662
  • 10
  • 21