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

Re-writing while loop to include do loop.

This question is confusing me. It is asking to insert a do loop into the code below, to make it work better.

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

So my take was to do:

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

My brain hurts. I know I'm not doing something obvious but I'm drawing a blank. I'm not finding too many simple examples to help clarify this loop for me.

I'm seeing the prompt loop as long as the password "sesame" is not entered (while condition), and it runs at least once because of the do loop. I also tried:

do { secret; } while (! "sesame") { } etc

... but it came back saying I need the prompt inside the loop. Confused.

Thanks

(P.S. Not sure why formatting is all screwed up after I post.)

Steven Parker
Steven Parker
231,236 Points

Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:
Or watch this video on code formatting.

1 Answer

Steven Parker
Steven Parker
231,236 Points

Your first "take" was close, but one of the advantages of the "do" loop is that you will not need to call "prompt" before the loop, since the one inside will run before the loop conditional is evaluated.

Also, in the structure of this kind of loop, the loop body (enclosed in braces) is between the "do" and "while" keywords, so there would not be a body (or pair of braces) following the loop conditional like there is in a plain "while" loop.

Once you fix those issues, you should pass the challenge.