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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Yi Ho Wong
Yi Ho Wong
6,377 Points

while ( ! correctGuess )

I can run the program correctly but I am not sure about the 'while' condition ( ! correctGuess ).

As the value of the variable 'correctGuess' is false initially, as long as the guess does not match the random number, correctGuess should still be false. Then why do we put a '!' in the 'while' condition to turn it to be true? Is it because we need to keep the 'while' condition to be true to loop again until the guess matches the random number, then the correctGuess is true and put a '!' in front of it to make it false in order to exit the loop?

2 Answers

Jacob Herrington
Jacob Herrington
15,835 Points

In JavaScript you can use that syntax for boolean operations with several decision structures for example:

/* While true contains a falsey value (which is never) */
while(!true){
  //this never happens
} 
/* While false contains a falsey value (which is all the time) */
while(!false){
  //always happens
}

if(!false){
  //always happens
} else {
  //this never happens
}

The ! operator simply means "not". So you can read that while loop as, "While correctGuess is false, continue this loop." So the game will continue until the correct value is guessed.

Gregory Ledger
Gregory Ledger
6,116 Points

I think the op is right. In the console log I ran,

var x = false; 
!x; --returned true.

So while a condition is true, the code runs. It only becomes false after the condition is set to true. Now the while 'sees' x = true, so !x returns false, so the code stops running.