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
10,917 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.