Code not working help!

Code not working help!
0

#1

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!");

#2

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


#3

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


#4

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!");

#5

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


#6

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?


#7

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


#8

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!");