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

Donald Lobree
Donald Lobree
10,307 Points

do while loop

This code seems to work in another js environment: repl.it, but treehouse isn't accepting it. It wants the prompt action outside the loop. However, when I do that, I get an infinite loop.

Again, as far as I know after testing it, the following code should be correct:

var correctGuess = false; do{ var secret = prompt("What is the secret password?"); if( secret === "sesame" ) correctGuess = true; } while (correctGuess === false)

document.write("You know the secret password. Welcome.");

What am I missing?

script.js
var correctGuess = false;
do{
  var secret = prompt("What is the secret password?");
  if( secret === "sesame" )
    correctGuess = true;
} while (correctGuess === false)

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>

HI You forgot a {} on your if statement. You should fix that and be good to go!

Shay Paustovsky
Shay Paustovsky
969 Points

Hi,

You should create the variable that holds user's input from the prompt outside of the loop.

var secret;
do {
secret = prompt('What is the secret password?');
if (secret === 'sesame') {
   correctGuess = true;  
   } while (correctGuess === false)
}
Antti Lylander
Antti Lylander
9,686 Points

No if statement is needed here. Just declare the variable secret before the loop. As for the loop, you do not need to write any new code, just re-arrange it in the do while style. You can even use the original "secret !== "sesame" ".

1 Answer

Steven Parker
Steven Parker
229,657 Points

The challenge gives you a pretty good hint: "Bummer: You should declare the secret variable before the loop. Otherwise, you re-create that variable each time through the loop."

So just add "var secret;" before the loop and remove the "var" inside the loop to convert the declaration into a simple assignment.

Otherwise, you've got it. :+1: