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 trialRuobing Zhang
1,409 PointsAt 7:09 of the video, why you can just put line9 as: if ( correctGuess )?
At 7:09 of the video, why you can just put line9 as: if ( correctGuess )? What if the user didn't guess the number? Would it still console.log (' You guessed the number!') ?
2 Answers
Peter Vann
36,427 PointsIf statements use a conditional operator to determine program flow (if it evaluates to true, the code in the if statement's curly braces will execute, if it evaluates to false then it executes the else code, if there is any, or, if there is no else block, it will just skip the if block).
In effect:
( correctGuess === true )
will either evaluate to true or false, depending on the value of correctGuess. Consider this code:
if ( true ) {
// will always execute
}
therefore, if correctGuess = true, then
if ( correctGuess ) {
// will always execute
}
but if correctGuess = false, then
if ( correctGuess ) {
// will NOT execute
} else {
// will execute (if there is an else block)*
}
// *(otherwise) execution resumes here...
Does that make sense now?
I hope that helps. Happy coding!
Peter Vann
36,427 PointsAnother way to think of it relates to why the variable is named correctGuess in the first place (which is a very appropriate variable name for a boolean value, actually).
If it's true, then the guess is, in fact, CORRECT (DO go into the if block)
...whereas...
If it's false, then the guess is, in fact, INCORRECT (So, therefore, DON'T go into the if block, or run the ELSE code, if there is any)
Again, I hope that helps. Happy coding!
Peter Vann
36,427 PointsIn fact, you could probably improve the varible name to make the logic even more clear by renaming it to guess_is_correct.
Then the code would read:
if ( guess_is_correct ) { // === true
// execute this code...
} else { // === false, and therefore, guess is NOT correct
// then execute this code...
}
Again, I hope that helps. Happy coding!
Ruobing Zhang
1,409 PointsRuobing Zhang
1,409 PointsThank you!