I’m totally new at Javascript. I just learned about the WHILE loop and I’m trying to create a simple number guessing game, but it doesn’t seem to be working. The program is supposed to work like this: The player has 3 tries to guess the random number from 1-5. If guessed wrong, an alert gives a hint whether or not the number is higher or lower. If guessed right, the program congratulates the player and exits the loop. The condition ” ( guessCounter < 3 || +guess !== randomNumber ) ” doesn’t seem to be working though. Perhaps it’s something else. Any help understanding why it’s not working is appreciated. Thanks.
// Generate random number
const randomNumber = Math.floor( Math.random() * 5 ) + 1;
// Ask user for guess
let guess = prompt( "Guess a number between 1-5." );
// Create guessCounter
let guessCounter = 1;
// Allow only 3 guesses. Each wrong guess will hint if the random number is higher or lower. If guessed correctly, congratulate player and exit loop.
while ( guessCounter < 3 || +guess !== randomNumber ) {
if ( +guess < randomNumber ) {
alert(`You did not guess correctly. The number is higher.`);
guessCounter+= 1;
guess = prompt("Try again.");
} else if ( +guess > randomNumber ) {
alert(`You did not guess correctly. The number is lower.`);
guessCounter+= 1;
guess = prompt("Try again.");
} else {
alert(`You guessed the correct number. Congrats.`);
}
};