Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics Making Decisions in Your Code with Conditional Statements Boolean Values

At 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

If 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!

Thank you!

Another 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!

In 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!