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

Robert Kooyman
Robert Kooyman
4,927 Points

I lost overview here

I lost the overview and am not sure what I am doing right and wrong anymore. Anybody who can help out and lead me towards the correct code would be a life saver! Thanks alot

script.js
var secret = prompt("What is the secret password?");

do { secret
   }
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>
var  secret;

do {
  // Ask the user for the secret password.
  secret = prompt("What is the secret password?");
  // Whatever the user enters in to the prompt box will now
  // be stored in the secret variable.

  // if the secret variable does not equal "sesame" then the code
  // inside this code block will be constantly re-executed until the
  // secret variable equals "sesame";
} while (secret !== "sesame");

document.write("You know the secret password. Welcome.");

1 Answer

Benjamin Barslev Nielsen
Benjamin Barslev Nielsen
18,958 Points

A do-while is built in this way:

do {
  body (what should be repeated)
} while (condition)

The body is repeated as long as the condition is true.

The thing you want repeated is the prompt and therefore the line:

secret = prompt("What is the secret password?");

should be your body, and should be removed in line 6, as well as the {} which surrounds it.

In a do-while loop the body is executed before the condition check, and therefore you don't need the prompt before the loop, i.e., your first line should only declare the variable, but not assign a value to it.

I hope this helps.