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

Help, please.

I would really appreciate if someone helps me with this.

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>

2 Answers

Liam Clarke
MOD
Liam Clarke
Treehouse Moderator 19,204 Points

To convert the code to a do while loop, there are a few changes that will be made

  1. remove the initial value set on the var secrets, this is because a do while loop is run once before the while condition is checked. If we did not remove it, then the prompt will be shown twice.

  2. follow the syntax of the do while loop, its kind of like a while loop upside down when you compare between them

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

Thanks!

Rahul Saini
Rahul Saini
4,611 Points

It asked you to convert while into do while. The main difference between them is that While : Runs at least once and then check the condition, whereas while checks the condition first and then runs the code.

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