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

Adam Floyd
Adam Floyd
868 Points

Question about this code block.

do { var yourName = prompt("Who are you?"); } while (!yourName); console.log(yourName); I get most of this do loop. But "while (!yourName)" confused me. I now ! Is flipping the boolean value but there is no === true or === false. Can someone please explain. Thank you.

1 Answer

Gabbie Metheny
Gabbie Metheny
33,778 Points

I formatted your script to make it a little easier to read, see the Markdown Cheatsheet

do {
  var yourName = prompt("Who are you?"); 
} while (!yourName);
console.log(yourName);

You might want to check out the W3 Schools' page on JS Comparisons and Logical Operators, or just google "javascript logical not."

! is the logical NOT operator, meaning that saying !yourName is like saying not yourName, so it's telling JavaScript to run the loop while not yourName is true (or yourName is false), meaning while there's nothing stored in the yourName variable. "Do while" loops always run at least once, since the "while" condition comes after the code block, so if the user enters a name, it will be stored in the variable yourName, making the condition "!yourName" (not yourName) return false, meaning that the program will stop. If nothing is entered, "!yourName" will return true, and the loop will run again until the user enters a name and something is stored in the variable "yourName."

Loops will only run if the condition evaluates to true, so while saying (yourName = false) might look better to a human than (!yourName), the JavaScript interpreter will see a false condition and exit the loop, regardless of whether or not anything has been stored in the yourName variable.

Hope that helps!