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 trialBjörn Wauben
10,748 PointsRewriting While loop into Do...while loop
After I had some trouble with the original challenge of this while loop I finally passed the challenge. In another challenge I need to rewrite this while loop into a do..while loop.
I tried breaking it down into steps. I should write a "statement" which executes at least once as long as the condition is true. So I think I need to use prompt in the statement and test if the password is not equal to "sesame" in the condition so the loop runs untill the condition is false and matches "sesame" Is this thought-process correct?
if so I might have trouble with the syntax and that's why it doesn't pass the challenge.
(note: I left the original code as an example when I tried to pass the challnge I only have the do...while loop in the window)
var secret = prompt("What is the secret password?");
while ( secret !== "sesame" ) {
secret = prompt("What is the secret password?");
}
document.write("You know the secret password. Welcome.");
do { secret = prompt("What is the secret password?");
}
while (secret !== "sesame")
document.write("You know the secret password. Welcome.");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Jonathan Söder
7,428 Pointsah!
var secret;
do {
secret = prompt("What is the secret password?");
}
while (secret !== "sesame")
document.write("You know the secret password. Welcome.");
You need to declare the variable secret outside of the loop, but don't add any value to it. then you call it inside the loop, like above
Jonathan Söder
7,428 Pointsdoes it work when you add a semicolon at the end of the while? Or is it something else entirely?
Björn Wauben
10,748 PointsNo is says: "You only need to call the prompt() method once, and only inside the loop." But I think I do this. I tried to remove the variable but then it says that I need to declare it outside the loop.
Björn Wauben
10,748 PointsBjörn Wauben
10,748 PointsThanks. It works. Glad at least the loop part was oké.