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

Confusion over the "do...while" condition

I understand that if the conditional statement evaluates to false, nameCheck is reassigned to true. What I don't understand is how setting nameCheck to true exits the loop. Thus making the while condition evaluate to false.

Is this loop saying ... execute this loop as long as needed until nameCheck is "not false" or "true"?

Or is the evaluation of the condition more so this: (! + nameCheck). Meaning whatever the value of nameCheck is at the end of the loop, plug it into the condition. So if the conditional statement evaluates to false, nameCheck = true. Upon evaluation of the while, it reads (! + namecheck) ---> (! + true) ---> (false). Thus the loop ends.

Sorry about any confusion with regards to what I may be asking. I'm just looking for an explanation.

  var nameCheck = false;
  do {
    var accountName = prompt("Think of a name for your account");
    if (accountName === "") {
      alert("An account name is required for registration");
    } else {
      nameCheck = true;
    }
  } while (!nameCheck);

1 Answer

The ! (NOT) operator reverses the meaning of booleans, so it turns true into false and false into true. So if nameCheck is set to false it will be treated as true due to the !. Conversely if nameCheck is set to true then it will be treated as false

While loops (and if statements and pretty much any other conditional statement) will only run if the condition you given it evaluates to true. So the moment you set nameCheck to true the loop exits, since the ! operator turns that true into false when it is evaluated.