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 Boolean Values

Elena Paraschiv
Elena Paraschiv
9,938 Points

Can we add just one If statement instead?

Is it the same if we write like this :

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?');

if (parseInt(guess) === randomNumber ) {
correctGuess = true;
    document.write ("You got it!")
} 

else {
    document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}

instead of :

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?');

if (parseInt(guess) === randomNumber ) {
     correctGuess = true;

} 

if (correctGuess= true){
   document.write ("You got it");
}
else {
    document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}

3 Answers

No, it's not! If you look at this statement closely:

if (parseInt(guess) === randomNumber ) { correctGuess = true; document.write ("You got it!") } 

it is not the same as

if (parseInt(guess) === randomNumber ) { correctGuess = true;}

because here:

if (correctGuess= true){ document.write ("You got it"); } else { document.write('Sorry. The number was ' + randomNumber + '.'); }

you are not comparing correctGuess to true, you are assigning it. Try changing it to correctGuess == true or even correctGuess === true instead.

[Mod Note - Changed from comment to answer so it can be voted on or marked as best.]

Elena Paraschiv
Elena Paraschiv
9,938 Points

Got it . Thanks for the clarification Perry !

stevenstabile
stevenstabile
9,763 Points

I don't understand this. If you do it like Elena, IF the users guess is the same as the randomNumber, you set correctGuess from false to true and tell the user they are correct. ELSE you leave the correctGuess as false and tell the user they were wrong. Why would you have to compare correctGuess to true when that's the purpose of the guess === randomNumber line? Am I missing something?