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

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

Frank keane
Frank keane
8,074 Points

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!

1 Answer

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!