Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Arikaturika Tumojenko
8,897 PointsCan someone explain guess= getRandomNumber(upper) inside the loop?
So, how exactly the code inside the while loop works?
// variable created to define to upper limit of the random number
var upper = 10000;
// now we generate a variable which holds the number the computer has to guess. This code will generate a number from 1 to 10.000
var randomNumber = getRandomNumber(upper);
// we create a variable that will hold the computer's guesses
var guess;
// we create a variable that will keep track of the number of attempts the computer tried to guess
var attempts = 0;
function getRandomNumber (upper) {
return Math.floor( Math.random() * upper) +1; // let's say the value is 120, therefore
// randomNumber is also 20?
}
while (guess !== randomNumber) { // while 20 !== 20 - how does this work?
guess = getRandomNumber(upper); // guess = 20 in this case?
attempts +=1;
}
If var randomNumber is equal to the return of the getRandomNumber function, how can guess not be equal to randomNumber?
1 Answer
Jeremy V
11,110 PointsIt looks to me like randomNumber is being set 1 time, outside of the while loop. As long as the while loop is running, guess is going to continue to be set to a random number with an upper limit of 10000.
So, basically, your program assigns randomNumber a value of a random number with an upper limit of 10000.
Then every time the while loop runs, guess is assigned a different random number with an upper limit of 10000.
Does that help?
If you want to see this in action, add a console.log("randomNumber = " + randomNumber); after you set randomNumber. Then add a console.log("guess = " + guess); after guess is set inside your while loop.