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 Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Tow Boon Ng
Tow Boon Ng
14,507 Points

randomNumber is used twice in this video. Will this following scenario happen??

if (randomNumber === guess) , produce a number. e.g. 5 prompt , User guess prompt another number, e.g. 6

it is wrong, else statement will be called. and it also generates a randomNumber ? is this the same randomNumber, 5? or a different randomNumber.

i.e. IF statement, randomNumber = 4 user guess = 3. ELSE statement generates a different random number. randomNumber=3 coincidentally "Sorry the number you guess is 3"

1 Answer

jag
jag
18,266 Points

As long as the function that generates the random number isn't included in the loop then only one variable will be defined no matter how many tries.

If the random number is included within the loop then each time it will generate a new number and it can even generate the same number as it previous had.

Tow Boon Ng
Tow Boon Ng
14,507 Points

Hi @jag, do you mean the same loop basis on below comment in my code??

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
/*
the randomNumber in the if / else if statement are the same number
*/
if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
} 
else if (parseInt(guess) > randomNumber) {
    var guessLess = prompt("The number that I am thinking is lesser than "+ parseInt(guess));

    if (parseInt(guessLess) === randomNumber) {
      correctGuess = true;
    }
}
else if (parseInt(guess) < randomNumber) {
    var guessMore = prompt("The number that I am thinking is more than "+ parseInt(guess));
    if (guessMore === randomNumber) {
      correctGuess = true;
    }
}


// the randomNumber here is different from else if.  

if ( correctGuess ) {
    document.write('<p>You guessed the number!</p>');
} else {
    document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}
jag
jag
18,266 Points

Not sure how you would be getting a different number. I looped it through multiple guess and randomNumber doesn't change within the loop. The only way it would change is if you had a function outside that created a new loop and you called that function every time.