JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a `do...while` loop

Jonathan Adams
Jonathan Adams
6,073 Points

I am unable to figure this one out. Any help would be appreciated.

I can't figure out what I'm doing wrong with my do while loop

script.js
var secret = prompt("What is the secret password?");
do ( secret !== "sesame" ) {
  secret = prompt("What is the secret password?");    
} while ( secret = "sesame" );
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

tapio
tapio
Full Stack JavaScript Techdegree Student 18,477 Points

The first condition you used is exactly what you need. You just need to rearrange it a little bit:

We don't know what the user will type in. So you could just leave that question open by assigning secret an empty string:

var secret = "";

The code after do gets executed at least once without checking any conditions. So you can use that opportunity to prompt a question and assign the answer to secret. AFTER the user types in an answer, the answer will be checked against the condition following while:

do {secret = prompt("What is the secret password?")}
while ( secret !== "sesame" );

If the user does not type in 'sesame' the condition is met and the loop will keep looping. Once he gets it right and the condition (which assumes he gets it wrong) is not met anymore the rest of the code gets executed:

document.write("You know the secret password. Welcome.");

Good luck!