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 A Closer Look at Loop Conditions

Nelson J
Nelson J
7,411 Points

I don't see what's wrong with my guess the number program.

I don't see why my program never even loads.

// generate random number between 1 and 10
var randomNumber = Math.floor(Math.random() * 10 + 1);

// computer guesses 5
var guessNum = 5;

// counter 
var count = 0;


// while computer hasn't guessed the random number, increment the counter by one.
while (guessNum !== randomNumber) {
  count += 1;

// If the computer guesses random number,  log random number and number of attempts to the console. Otherwise, log the random number and the number the computer guessed.
  if(guessNum === randomNumber) {
    console.log("random number is " + randomNumber + " and it took " + count + " number of guesses");
  }
  else {
    console.log("random number is " + randomNumber + " and the computer guessed " + guessNum);
  }

}

Can you tell me what's wrong with it? Thank you very much.

2 Answers

guessNum should be one of the possible values for randomNumber so inside the loop

guessNum = Math.floor(Math.random() * 10 + 1);

Nelson J
Nelson J
7,411 Points

Thank you, that worked and I can see why now. :)

Your guess number never updates inside the loop. So unless the random number generated is 5 you have an infinite loop.

Nelson J
Nelson J
7,411 Points

I have updated the guessNum to be guessNum += 1 inside the loop but it won't work either.