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 (Retired) Making Decisions with Conditional Statements Document Your Code With Comments

Paul M
Paul M
16,370 Points

Why did the code only put if (correctAnswer) instead of, if (correctAnswer = true) ?

I saw in the code this fucntion. My question is why did he leave out the = true statement after correctAnswer?

4 Answers

The if statement checks for true or false. If you are already storing true or false in a variable you only need to use the variable name inside the conditional statement.

var correctAnswer = false;

/* 
* The variable contains false so the code inside the 
* brackets will not run 
*/
if ( correctAnswer ) {
   ...
}

/* 
* This will set the value of the variable to true and run 
* the code inside the brackets even though the first 
* value was false 
*/
if ( correctAnswer = true ) {
   ...
}

/* 
* This will compare the value of our variable to true and 
* return true if they match or false if they don't. could 
* also use '===' 
*/
if ( correctAnswer == true ) {
   ...
}
Steven Parker
Steven Parker
215,954 Points

First off, for a comparison it would need to be == (double equals). One equal sign is an assignment.

But the whole purpose of a comparison is to determine a true or false condition. If a variable is actually storing a true or false, there's no need to compare it to anything, just test it directly.

The part inside the parenthesis of an if statement is evaluated to a boolean. So if you supplied a statement like (correctAnswer == true), the value of correctAnswer would be inserted, i.e. (true == true) and that evaluates to true. If correctAnswer wasn't already boolean you could get unexpected results because the string 'true' is truthy and the value null is falsey, but the string 'false' is also truthy. So be sure to test your code for the intended behavior.

Garrett Levine
Garrett Levine
20,305 Points

if you have a variable in an if statement, you're basically checking to see if that variable EXISTS. if it does exist, it will return true, if it doesn't exist, it will return false.