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 Create a `do...while` loop

Immanuel Jaeggi
Immanuel Jaeggi
5,164 Points

help with do...while loops

I need to re-write this code using the do while loop. Here is my code:

var secret = 'sesame';

do {

}

while ( secret !== "sesame" ) { secret = prompt("What is the secret password?");
} document.write("You know the secret password. Welcome.");

In my opinion, I need to prompt the user in the do..part to enter the secret password, however this is obviously false. In the do..part, any code runs atleast once. So why is it that when I type in a prompt, it's wrong? What should go in there?

script.js
var secret = 'sesame';


do {

}

while ( secret !== "sesame" ) {
  secret = prompt("What is the secret password?");    
}
document.write("You know the secret password. Welcome.");
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

1 Answer

Joel Bardsley
Joel Bardsley
31,246 Points

Hi Immanuel, there's a couple of issues here:

  • As you have the secret variable set to "sesame" on line 1, the while condition is never met.
  • Unlike a regular while loop, the code is executed in the do statement before checking whether the while condition is equal to true or false.

Since the code to prompt the user for a password needs to run at least once, it makes sense to do this in the do statement before checking whether the password is correct. I won't give you the full answer, but hopefully the following will help you:

var secret; // We don't have a value for this yet, so let's create a placeholder before prompting the user for a value.

do {

  // Prompt the user for their secret password and store it in the placeholder variable

} while (secret !== "secret") // If this is true, the do statement runs again until the correct password is given.

If you continue to struggle, either rewatch the previous video or check the do...while loop documentation to see where you might be going wrong.