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

Shoaib Khan
Shoaib Khan
7,242 Points

I need some help in parsing some JavaScript code for this code challenge.

I can't seem to get this code to accept. What am I doing wrong? I have created a test workspace and when I run the code I get prompted for the password and type in "sesame" and then I am prompted again and then I retype the password and then the code will run the while statement and then write to the document. I can't seem to get it to write to the document the first time around. Please help.

script.js
var secret = "sesame";

do {
  var secret = prompt("What is the secret password?");
  if ( secret === "sesame" ) {
    document.write("You know the secret password. Welcome.");
  }
} while ( secret !== "sesame" )
  secret = prompt("What is the secret password?");
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

3 Answers

Linas Mackonis
Linas Mackonis
6,721 Points

Hi Shoaib,

You write the do while loop like this:

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

You are re-declaring the secret variable for the second time in the do code block, which you should avoid.

First you declare the variable then you assign the prompt value inside the do code block.

The loop runs the same question until a certain condition is met. In this case secrete not being equal to a 'sesame'. When the word is equal to 'sesame' the loop stops and the code can proceed to the write() function.

Hope that was helpful!

Shoaib Khan
Shoaib Khan
7,242 Points

I was able to figure it out!

var secret = "sesame";

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

Thanks for all the replies!