JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Nelson J
Nelson J
5,685 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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,702 Points

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
5,685 Points

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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,702 Points

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
5,685 Points

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