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

Can someone help with this do while loop assignment. I can't figure it out

I can't figure out why this is wrong and what is the correct way to turn the commands into a do while loop

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

Henrik Hansen
Henrik Hansen
23,176 Points

The do/while loop is written like this

do {
    // Code to execute
}
while ( 
     // Statement that is true
);

You can read about it on W3schools

Brian Polonia
Brian Polonia
25,139 Points

Place the following code in your script.js and it should work:

var secret;  //<-- declare variable outside of loop to save on memory

do {
  secret = prompt("what is the password?"); //<-- set secret to equal a prompt asking for the password
} while (secret !== "sesame") //<-- as long as secret isn't equal to "sesame" the code block above will continue to execute
    if (secret == "sesame") { //<-- once loop is ended by secret being equal to sesame this conditional checks for a match
        alert("you know the password"); //<-- if secret in fact is equal to sesame then here I used an alert but you can use what you'd like to give message
    }