Code not working help!

Im trying to make this age guessing random game work but its not working properly, wont exit loop when i type in my age and wont display alert message when typing 30 or 25. Help!

var age = 22;

var input = prompt("Guess my age");

while (input !== age) {
   if (input === 30) {
       alert("Nope, try again");
   }  else if (input === 25) {
       alert("Quite close");
   }

   var input = prompt("Guess my age");


}
console.log("Yay you guess it!");

Try using != and == instead of !== and ===.

Oh thanks it was about string comparing to numbers, my bad. Thanks for your answer.

Also, there is no need to have two prompts of the same message…

var age = 22;
while (input != age) {
   var input = prompt("Guess my age");
   if (input == 30) {
       alert("Nope, try again");
   }  else if (input == 25) {
       alert("Quite close");
   }
}
console.log("Yay you guess it!");
1 Like

Good to know that too. Thanks. But i wanted that prompt message to go in loop while input is not equal to age thought.

And does it mean that loop change in this case that prompt message doesnt have to be put in bottom of code block in while loop?

It should be at top of loop, to avoid an extra iteration of the while loop.

1 Like

A slight variation on your game would be to have it tell the user if the guess is higher or lower and if the guess is close (plus or minus 3 years).

var age = 22;
while (true) {
   var input = prompt("Guess my age");
   if (input == age) {
     break;
   }
   var msg = 'Nope, try again.  Your guess is too ';
   msg += input < age ? 'low' : "high";
   if (Math.abs(input-age) <= 3) {
     msg += ", but you are quite close"
   }
   alert(msg);
}
console.log("Yay you guess it!");
1 Like