JavaScript

Michael Braun
Michael Braun
5,250 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
177,507 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
5,250 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
177,507 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
5,250 Points

Awesome. Thank you for your help Steve!

Steven Parker
Steven Parker
177,507 Points

Michael Braun — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!