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

Ethan Hou
Ethan Hou
658 Points

I have no idea what I am doing wrong. Can someone please help me fix my code. Im sorta confused on the do while code :(

Am I doing the second part correct? I feel like my first part makes sense. but the while part im not too sure. I know it stops running once its false.

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

do{
  if(secret === "sesame") {
    correctGuess = true;
    document.write("You know the secret password. Welcome.");
  }
} while(!== correctGuess );
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

Stephan Olsen
Stephan Olsen
6,650 Points

You've got the syntax of the do...while loop correct.

do {
  // do something
} while(condition)

You should be careful with altering the code too much, and not do more than what is asked of you. Let's break down the original code you're given, line by line.

// Initializing secret variable
var secret = prompt("What is the secret password?");

// while(condition)
while ( secret !== "sesame" ) {
  // doing something inside
  secret = prompt("What is the secret password?");    
}
// doing something outside
document.write("You know the secret password. Welcome.");

So what you need to do, is move what you do inside the while loop, into the do { } scope and put the while(condition) after. The document.write must still be outside the do...while loop. Furthermore, since you'll be using a do...while loop, it will run what's inside the do { } scope once before checking the condition. This means that at the top of your code, you should only declare the secret variable instead of initializing it - you should not assign it a value.

Let me know if this makes sense :)

Ethan Hou
Ethan Hou
658 Points

Thank you very much! Makes sense!