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

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

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
5,527 Points

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

Davie Chen
Davie Chen
2,929 Points

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

Thank you, Andrew. Very clear and educative answer.