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

origin of var guess vs. var randomNumber

I'm having a hard time wrapping my head around the origin of 'var guess' vs 'var randomNumber' For example, the logic reads that:

var randomNumber = getRandomNumber(upper); 

function getRandomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;

while ( guess !== randomNumber ) {
  guess = getRandomNumber(upper);
  attempts += 1; 

So this is how I am reading the above:

var randomNumber = getRandomNumber(upper) = var guess

By that logic, how does var guess NOT EQUAL to randomNumber every time? I'm confused as to how var guess results in a different number than what results from the getRandomNumber function.


3 Answers

leong shing chew
leong shing chew
5,618 Points

Its true that :

var guess = getRandomNumber(upper);
var randomNumber  = getRandomNumber(upper);

But the one thing to note is that getRandomNumber(upper) returns a "Random" number every time its invoked.

In the code, everytime the following is invoked, guess gets a new "Random" number guess = getRandomNumber(upper);

I understand that the getRandomNumber(upper) results in a new random number every time. I don't quite understand your last sentence however.

leong shing chew
leong shing chew
5,618 Points
guess = getRandomNumber(upper);

the above at every attempt will return a new number, that part you understand, correct?

As "randomNumber" and "guess" both call the function separately, they both gotten possibly a different number.

In no place the the above code does it specify that

guess = randomNumber

Aha, thanks for the clarification leong. In my mind, I was thinking that getRandomNumber(upper) was generating the SAME random number in both locations it was called up.

I think they should change this example because this made my brain overheat so hard as well :D Thanks leong ;)

Great question and answer. I was puzzled by this as well. Thanks!