Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,777 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!