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
Stephen Chamroeun
7,095 PointsI want to make sure I understand this code correctly!
I'm just going to give an explanation of the code below to make sure I understand it correctly. If I am missing anything, can the community let me know please?
From top to bottom, the getRandomNumber function is producing a random number from 1 to 100 and storing that value within randomNumber. At the moment, guess has no value, so that when the while loop checks the condition, it evaluates to as true. The code block then runs, the guess variable is now given a value by utilizing the getRandomNumber function and the 1st attempt is recorded. The process is then repeated until the value given to guess is matched correctly with the randomNumber produced each time. That sounds right, correct?
var upper = 100;
var randomNumber = getRandomNumber(upper);
var guess;
var attempts = 0;
function getRandomNumber(upper) {
return Math.floor(Math.random() * upper) + 1;
}
while ( guess !== randomNumber ) {
guess = getRandomNumber(upper);
attempts += 1;
}
document.write("<p>The random number was: " + randomNumber + ".</p>");
document.write("<p>It took the computer " + attempts + " attempts to get it right.</p>");
1 Answer
Joseph Wasden
20,407 PointsFirst, to answer you question, yes (...pretty much, but perhaps not exactly. Do you understand at which point the assignment of randomNumber occurs? it's a little tricky).
Have you encountered the concept of hoisting yet? Or the idea that javascript has 2 phases, compilation and execution?
It seems you have a pretty good grasp of things, but those concepts could also be helpful in understanding what is going on with any javascript code. Or perhaps it's not worth going into at the moment. :)
Stephen Chamroeun
7,095 PointsStephen Chamroeun
7,095 PointsNo, I’m not quite there yet . But I will be soon ?