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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

The guessed answer is never good, forever in a loop?

I've pulled half of my hair out, why is this code not working? Thanks in advance.

var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false;

function getRandomNumber( upper ) {
  var num = Math.floor(Math.random() * upper) + 1; 
  return num;

do {
  guess = prompt('give us a random number between 1 and 10');
  guessCount += 1;
  if (parseInt(guess) === randomNumber) {
    correctGuess = true;
} while ( ! correctGuess )
  document.write('<p> Congrats! You guessed it right, it took you ' + guessCount  + 'attempts </p>');

3 Answers

Aakash Srivastava
Aakash Srivastava
5,415 Points

Hey baderbouta , I copied your code and it works for me...
It may took many attempts to guess the right one , i guessed correctly in 66 attempts.
Best way would be to check the code would be by lowering the value from 10 to 3 or 4 and you will take lesser attempts to guess it.
Hope it helped :)

Thanks a lot!

I had this same issue and I can't understand why it takes so many attempts.

I changed upper to 3, so it could only be one of three numbers, and yet it still took me hundreds of attempts to guess the right number. How is this possible? I get that it's technically random each time, but that's incredibly statistically unlikely.