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

Routine Poutine
Routine Poutine
25,845 Points

You only need to call the prompt() method once, and only inside the loop. Hint: Declare the secret variable before the l

Hi,

I understand a do loop to be one that has a block of code run before checking a condition:

do { run this code first } (check this condition after; if true, do it until false)

However, I'm not sure what I am doing wrong here. For some reason I cannot enter the code correctly.

do { secret = prompt("What's the password?"); } while ( secret !== "sesame")

Seems to be correct. At least, I cannot understand how this would require multiple instances of the code block, unless the condition is false.

Please help me understand, I watched some of the videos again and am still having a hard time doing this correctly.

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

do {
  secret = prompt("What is the secret password?");
}
while ( secret !== "sesame" ) 

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>
Routine Poutine
Routine Poutine
25,845 Points

I found the answer online, but do not understand it. Why must we only declare a variable, but not define it, until the do loop is stated?

why do we need:

var secret;

why does this not work?

var secret = post('What is the password?');

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 48,728 Points

Because the do loop will execute at least once you'd be asking the question twice. Try your code in a workspace and enter sesame.

Routine Poutine
Routine Poutine
25,845 Points

Oh. Are you saying that defining the variable is actually calling the function, then putting it in a variable? I think I missed that part of the logic. Thanks for your help!