0

My code keeps running infinitely for some reason and I don't know how to fix it, can anyone help pls?

I'm trying to make a game using javascript where the user tries to guess the randomly generated number. There supposed to have infinite tries til they guess the number correctly. Every time they guess console.log will either tell them they guessed too high, low, out of range, or they won. For some reason whenever I guess with VALID NUMBERS it just keeps going infinitely and never output anything. Thanks. My code: // Sets the highest amount that the computer can randomly output let maximum = 10; // Generates a random number let randomNumber = Math.floor(Math.random() * maximum) + 1; // Stores the value if the user is still playing let stillPlaying = true; // Asks the user to guess the number while (stillPlaying) { let userGuess = prompt("Guess a whole number from 1-" + maximum + ":"); userGuess = parseInt(userGuess); if (userGuess < 1 || userGuess > maximum) { console.log("That's out of range"); } else if (userGuess === randomNumber) { console.log("You guess the number! Yipee!"); stillPlaying = false; } else if (userGuess > randomNumber) { console.log("You guessed too high!"); } else if (userGuess < randomNumber) { console.log("You guess too low"); } }

3rd Jan 2025, 3:25 AM
Christopher Keith Rivera
Christopher Keith Rivera - avatar
4 Answers
+ 7
Christopher Keith Rivera Two issues The first issue lies within the prompt() function The second issue is that the stillPlaying variable is not being updated correctly after the game is over. Here is the correction(s): https://sololearn.com/compiler-playground/WPy7PZKH6Q5D/?ref=app
3rd Jan 2025, 4:33 AM
BroFar
BroFar - avatar
+ 5
It's good to provide an exit strategy so that the player is not forced to play... https://sololearn.com/compiler-playground/WjooaYstlIB8/?ref=app
3rd Jan 2025, 9:11 AM
Bob_Li
Bob_Li - avatar
0
BroFar can you please explain why the original code was wrong? Isn’t stillPlaying started out as true and when it is false it should stop. Why did you need to break in order to stop? Also, I don’t see any difference as how you did the prompt function and how he did it.
3rd Jan 2025, 1:49 PM
Zvi
Zvi - avatar
0
Thanks for the help!
3rd Jan 2025, 1:55 PM
Christopher Keith Rivera
Christopher Keith Rivera - avatar