Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a `do...while` loop

Page Petty
Page Petty
813 Points

To DO or not to Do

My response is: No, I don't think it would be better in a do...while loop. It works fine the way it is and I can't figure out how to turn it into a doodoo loop.

script.js
// This works the best. I have no idea how to make it into a  do...while loop :P
var secret = prompt("What is the secret password?");

while (secret !== "sesame") {
  secret = prompt("That's not it! Try again");
}
document.write("You know the secret password. Welcome.");


// I have tried this and a bunch of other ways, but nothing else works
var secret = prompt("What is the secret password?");

do {
  secret;
}

while (secret !== "sesame") {
  secret = prompt("That's not it! Try again");
}
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>

1 Answer

Bjorn Beishline
Bjorn Beishline
12,934 Points

The trick is to define the variable secret before the do...while loop.

The reason you do this, is because the while part of the loop needs to compare the variable secret to sesame, and if secret isn't defined, well... your code won't work

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

look at (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while) for further reference.