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,203 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.