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.
Function is only run once?
A bit confused about the guess. It’s said in the video that the loop will run until guess matches the original random number. This implies the getRandomNumber function only runs once, and not every time it’s called.. the way I understand this loop is that each time it’s entered guess is given the value getRandomNumber returned in the previous loop. Random number is updated each loop right? Thanks!
Hey Frank, so if you'll notice, randomNumber is defined at the top of the file and it is outside of the loop, so this variable is only updated once. If you'll notice, the while loop compares guess to randomNumber, not the actual call to the function. Inside of the while loop, guess is being updated to a call to the getRandomNumber function. This means that the variable "guess" is updated with a random number value every time the loop runs. This loop will run as many times necessary until the "guess" value matches the value stored in "randomNumber". The loop will also update the counter each time it runs which results in the amount of attempts it took the computer to guess the randomNumber. So if I believe I am understanding your question properly, the most simple way to put it is that the randomNumber variable is only set once because it is not declared inside of a loop, but the guess variable is set every time the loop runs. Let me know if this clears things up for you, happy to help!