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 trialBrian Campbell
12,544 PointsBelow is the code for the last code challenge. This would work better as a do...while loop. Re-write the code using a do
Help! I'm stuck on this question and I tried multiple sources to learn how to solve this. Still no luck...
do {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.");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Marcus Parsons
15,719 PointsHi Brian,
do while blocks follow this pattern:
do {
//some code
}
while (somethingIsTrue)
If you read the words as I wrote them it says "do some code while something is true".
The first step is to just create the secret
variable. There's no need to set it equal to anything because of the next step which involves the do while loop. Do while loops always execute the code within the code block first before checking the conditional statement (the statement inside the parenthesis beside while).
This means that once we create the secret
variable, we can prompt for the secret inside the do while loop because it will automatically execute before it checks whether secret is not equal to "sesame". As long as secret doesn't equal "sesame", you'll have to keep guessing until you get it.
Here is that in action:
var secret;
do {
secret = prompt("What is the secret password?");
}
while (secret !== "sesame")
document.write("You know the secret password. Welcome.");
Jacob Mishkin
23,118 Pointsvar secret;
do {
secret = prompt("What is the secret password?");
}
while ( secret !== "sesame" )
document.write("You know the secret password. Welcome.");
you need to change up the code a bit. here is a great resource on do while loops:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while