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

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,242 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 !