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

Jonathan Martin
PLUS
Jonathan Martin
Courses Plus Student 1,942 Points

Why the IF statement has no condition? "if( correctGuess )" in this loop example?

<!-- JAVASCRIPT #36 --> <script type="text/javascript">

var randomNumber = getRandomNumber(10); var guess; var guessCount = 0; var correctGuess = false;

function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; }

while (guessCount <= 10) { guess = prompt('I am thinking of a number between 1 and 10. What is it?'); guessCount += 1; if (parseInt(guess) === randomNumber) { correctGuess = true; break; }
}

if( correctGuess ){ // why there's no other conditions. document.write('<h1>You guessed the number!</h1>'); document.write('It took you ' + guessCount + ' tries to guess the number ' + randomNumber); } else{ document.write('<h1>Sorry Wrong!</h1>'); }

</script>

1 Answer

Jake Lundberg
Jake Lundberg
13,965 Points

If statements actually only take one parameter...a boolean (true or false) value. In many cases, you are going to be using conditional operators to compare two or more things, like this:

if(a > b) {...}

but even though you have 2 operands, and 1 operator, this actually just equates out to a true or false value, and that is what is passed to the if statement.

so if a = 1 and b = 2, this statement would obviously be false, so it would be the same as passing:

if( false ) {...}

because of this functionality, you don't have to actually compare things within the parenthesis of the if statement...in your case, you have already determined if correctGuess is true or false elsewhere in your code, so you can just pass that into the if statement by itself...

Does that make sense?

I hope this helps!

Jonathan Martin
Jonathan Martin
Courses Plus Student 1,942 Points

"If statements actually only take one parameter...a boolean (true or false) value. In many cases, you are going to be using conditional operators to compare two or more things,"

This is the answer enlightened my mind. Thank you very much. I really appreciate this.

Best Regards, Jon