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

sahil shrestha
sahil shrestha
3,799 Points

This is the code we used in the last code challenge. After learning about do...while loops, don't you think this would w

This is the code we used in the last code challenge. After learning about do...while loops, don't you think this would work better in the do...while style? Re-write the code to use a do...while loop.

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

2 Answers

Andrew Hinkson
Andrew Hinkson
14,055 Points

So there is a few things.

A do/while loop is run first then the comparison is done after. You can do away with your if statement in the do body and also the return. The challenge just wants you to rewrite the original code into a do / while loop.

A do/while loop looks like this:

do { //this is the code you want to run } while (something is true)

The way they have it set up they want the prompt to show up until you put the word 'sesame' in. So you keep the variable declaration at the top but move the prompt into the body of the loop.

var secret; do { secret = prompt("What is the secret password?"); }

then in the while portion you would add your comparison. They are saying until the word 'sesame' is given to the prompt it will keep looping.

while (secret !== "sesame")

Then outside of the loop you will write to the document.

Overall:

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

Hope this helps

Elyse Dawson
Elyse Dawson
4,407 Points

THANK YOU. Still wrapping my head around this concept and the new syntax.

Davie Chen
Davie Chen
2,871 Points

Thanks a lot, Andrew! Nice to see how clean and simple the code can be.

Thank you, Andrew. Very clear and educative answer.