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

Michael Braun
Michael Braun
6,753 Points

Why - correctGuess = false; wouldn't while(! correctGuess); make the the condition true from the beginning?

As described in the title, I can't wrap my head around the logic in this example. If

correctGuess = false

do { } while ( ! correctGuess);

Can somebody help me understand the logic behind this? If the ! operator turns the boolean value around, wouldn't ( ! correctGuess) be "true" from the start since it's set to "false"?

3 Answers

Steven Parker
Steven Parker
229,732 Points

You're right that "! correctGuess" would be true, which means the loop would keep repeating.

When the guess is right, then "! correctGuess" becomes false and the loop ends.

Michael Braun
Michael Braun
6,753 Points

I think I'm starting to understand.

Please let me know if I'm understanding this correctly. So basically "while" is not comparing the statement in the while(condition) with "var correctGuess." The driving factor behind the execution of the loop is the fact that the while loop is waiting for the "false" boolean to exit. Since ! correctGuess evaluates to "true" once correctGuess is switched to true, the opposite will be applied in while (! correctGuess). Which evaluates to while(false) so the loop is exited. No comparison with any value here, just true or false essentially?

Is my thought process correct here?

Steven Parker
Steven Parker
229,732 Points

Yes, the boolean is tested directly without a comparison. But you made one error, here's a corrected version:

! correctGuess evaluates to "false" once correctGuess is switched to true

Michael Braun
Michael Braun
6,753 Points

Awesome. Thank you for your help Steve!