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

sebbe12
sebbe12
4,015 Points

while (randomNumber !== guess) { guess = getRandomNumber(upper); attempts += 1; }

while (randomNumber !== guess) { guess = getRandomNumber(upper); attempts += 1; }

I don't understand how this one works

2 Answers

Brendon Butler
Brendon Butler
4,236 Points
while (randomNumber !== guess) { // loop while the random number is NOT equal to the guess
    guess = getRandomNumber(upper); // get a new random number and set the guess variable to this new number
    attempts += 1; // increment the amount of guesses
}

// any code after this block will be run once the random number IS equal to the guess.

Basically, you're just looping until the computer "guesses" the correct number. And every time it makes a new guess, it adds 1 to the attempts variable. So that you could say something like "In 14 attempts, the correct number was guessed!"

sebbe12
sebbe12
4,015 Points

I see we store the new getRandomNumber(upper) we get after each time the computer is wrong and store it to guess. I was thinking that guess was equal to getRandomNumber(upper) while it was not equal. I was like what.

Joshua Swilling
Joshua Swilling
1,135 Points

hey sebbe i had a little rough time with this concept for a while , i developed a game out of it maybe this will help if you still had questions bro -- https://w.trhou.se/ft18pgwb4m

Dinesh Kumaar Rajendran
Dinesh Kumaar Rajendran
3,395 Points

HI Joshua Swilling,

Excellent explanation ! Thanks much !