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

Ran Wang
Ran Wang
Full Stack JavaScript Techdegree Graduate 30,601 Points

Replace the "guess" in the while condition with the call of function?

Other parts being the same, why my browser ran into endless loop when I replace the 'guess' with getRandomNumber(upper)'?

˜˜˜ while (getRandomNumber(upper) !== randomNumber) { getRandomNumber(upper); attemps += 1; }

˜˜˜ my idea is to call the function and it will each time return a value, if this value does not equal to the randomNumber, then call the function to run again in the loop.

For me, the above code seems logical, but the browser told me no.

3 Answers

Steven Parker
Steven Parker
173,876 Points

It would help to see your whole code, this part doesn't look like it would cause your issue.

But you can remove the 2nd call to "getRandomNumber", it doesn't really do anything now that "guess" has been removed except slow things down.

If you still have an issue please post the complete code. And the three marks that would indicate code for formatting are accents ("back-ticks").

Ran Wang
Ran Wang
Full Stack JavaScript Techdegree Graduate 30,601 Points

thank you for your help, my whole code is as follows:

var upper = 100000;
var randomNumber = Math.floor(Math.random()*upper)+1;
var countGuess = 0;
var guess;

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

while (GetRandomNumber(upper) !== randomNumber) {
  GetRandomNumber(upper);
  countGuess+=1;
}

document.write("The number is " + randomNumber + ", it took me " + countGuess + " times to guess it out.");
Steven Parker
Steven Parker
173,876 Points

I still don't see anything wrong. When I tried the code, I got this response:

The number is 58577, it took me 180246 times to guess it out.

Removing the redundant call speeds it up but doesn't affect the final result.

Steven Parker
Steven Parker
173,876 Points

FYI: You can get syntax coloring if you add "js" to the first set of ticks. :point_right: ```js

Jeff Sanders
PRO
Jeff Sanders
Pro Student 7,098 Points

There are in fact some major problems with this code.

  1. your var guess does nothing
  2. the GetRandomNumber call within the while loop is unnecessary because you aren't storing that value anywhere
  3. you aren't storing the computer's guess anywhere, so the program is very limited. For example, you couldn't analyze each guess if that became a requirement later on down the line