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 trialUnsubscribed User
3,436 PointsThe while condition confused me
The question has two parts:
1- The condition confused me. The instructor used the following code:
while ( !correctGuess)
What we want is to keep the loop running until the number is guessed. Here is the logic in my head: The number is false by default and then we added "!" which will make it true. The instructor says in the video that adding "!correctGuess" will make the loop run as long as the correctGuess is false. It seems that I'm missing something here.
2- Can we use the following instead of what was used in the video?
while (guess !== randomNumber)
3 Answers
jared eiseman
29,023 PointsHi Moe,
Another way to think about this is if you were to write out the expression in longhand (IE: correctGuess === false). This expression evaluates to true, as long as correctGuess is set to false. While loops run for as long as the expression it is provided evaluates to true. So we actually want !correctGuess to evaluate to true, so that the while loop runs.
Soon as the correctGuess has been made, and it's value is now set to true, !correctGuess evaluates to false, which then breaks the loop.
Hope this helps some
Nate Baker
17,247 PointsI had the same question. Jared, thanks for breaking that down. That makes perfect sense now.
Peter Stone
Front End Web Development Techdegree Graduate 20,124 PointsI'm still confused on this.... (! correctGuess ) doesn't evaluate to true, because correctGuess already equals false... so ! correctGuess = not false.
jared eiseman
29,023 PointsRight, so if correctGuess === false, !correctGuess is true. Because not false is true. While loops will only run as long as the expression passed to it evaluates to true. So when the correctGuess has been found, and is set to true, not true (!true) equals false, which makes the loop stop running.
Hope maybe this helps? sorry for the late reply.
David Soards
18,368 PointsDavid Soards
18,368 PointsNice breakdown. Thanks