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

do while loop

I am trying to rewrite this code using a "do while loop", but is not working . I am not sure what i am doing wrong here. Any idea?

script.js
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.");
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Steven Parker
Steven Parker
229,732 Points

It doesn't look like you've modified the provided code yet. Give it a try and the post your post-modified code if you still have trouble.

Andy Durette
Andy Durette
31,183 Points

I tried this out and it worked for me.

The var statement still exists outside for scope reasons.

Meanwhile the do part of the statement holds the executable code and loops through until the while condition is met. Steven Parker Hopefully this is more acceptable?

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

You're right about having the "var" before the loop, but it should be only the declaration. The assignment part should still be done inside the loop, so it will continue to ask for a password until it gets the correct one.

And the statement acknowledging the correct entry should be done after the loop.