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

Michael Lawinger
Michael Lawinger
33,581 Points

Do... While Loop Logic

I'm struggling with this question: 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.

var secret = prompt("What is the secret password?");
do {
while ( secret !== "sesame" ) {
  secret = prompt("What is the secret password?");    
<!DOCTYPE html>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
<script src="script.js"></script>

1 Answer

Steven Parker
Steven Parker
230,230 Points

Struggling with form or application?

You didn't say if you were having trouble with what the form of the loop would look like, or how to apply it to this situation. But I'll guess that it's the latter, since syntax guides are easily found online like at this MDN page.

So here's some hints about how you might apply the do...while to this situation:

  • remember the loop has only one code block, it goes between do and while
  • the same assignment made in the original loop block can be made in the block here
  • but instead of declaring the variable with the assignment, declare it before the loop
  • the only call to propmt will be inside the loop block