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

Kon Kim
Kon Kim
14,821 Points

do while confusion

keep getting error message that prompt only has to be called once and within the loop. so i'm confused

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>

2 Answers

maryam aljimaz
maryam aljimaz
8,051 Points

Just remove the question from outside the do while loop. Because you will be asked the question twice. Remember do while loop executes at least once and then checks for the condition.

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Kon;

You are very close. Just declare that secret is a variable outside the do... while loop without assigning it a value. Value assignment can occur inside the loop.

ExampleDoWhile

var someVariable;

do {
// do something interesting here
someVariable=prompt("Ask for input");
} while (someVariable != "some answer") ;
document.write("Great input");

Okay, my verbiage there is pretty lame, but the important things are there, right? We have declared a variable outside our loop. We keep getting input from a user inside the loop and assigning it to our variable. The while portion checks the inputted response we receive for a value and until that value is entered it keeps asking for input... over... and over... and over... Once achieved we can move on.

So what's the big deal of defining the variables outside of the loop? First, in my mind, is readability. After that there are some variable scope issues that come into play. If you are interested in those spend some time on Google reading about how JavaScript handles variable declarations and the various scope issues in JavaScript like function versus block scope and scope hoisting. The MDN docs on var would be a good place to start as well.

Happy coding and post back if you have further questions.

Ken