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

Routine Poutine
Routine Poutine
26,050 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
26,050 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

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
26,050 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!