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

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
215,954 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
215,954 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!