Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Terry Babyuk
Terry Babyuk
6,751 Points

Guess a number game using "while loop"

Hi guys,

I'm hoping someone can shed some light on this. I'm just practicing my loops with a game that asks the user to guess a random number between 1 and 10. When the number is guessed, they get an alert saying "You guessed correctly!". The problem is, my program seems to run indefinitely no matter how long I try to guess the numbers. It's almost as if it's not registering the correct number. What did I do wrong with my code?

const randomNumber = getRandomNumber(10);

function getRandomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;
}

let guess;

while (parseInt(guess) !== randomNumber) {

  prompt("Guess a number between 1 and 10:");

}

    alert("You guessed correctly!");
Adam Pearson
Adam Pearson
16,112 Points

Simple fix, you're just not assigning the user input from the prompt to the guess variable!

guess = prompt("Guess a number between 1 and 10:");

1 Answer

Terry Babyuk
Terry Babyuk
6,751 Points

Thanks Adam! I had a sense it was a simple fix, but my brain wasn't working well yesterday. Much appreciated!