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 trialMicah Dunson
34,368 Pointsdont understand 'do and while..' in this example
the question is to convert from while to a do-while loop. here's the 'while' code:
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.");
Here's my answer:
var secret = prompt("What is the secret password?"); do { secret = prompt("what is the password"); if (secret === "sesame") { document.write("You know the password. Welcome!"); } } while ( !secret)
Not sure what I'm doing wrong
var secret = prompt("What is the secret password?");
var secret = "sesame";
do {
secret = prompt("what is the password");
if (secret === "sesame") {
document.write("You know the password. Welcome!");
}
} while ( !secret)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Daniel Markham
10,976 PointsHi Micah,
You are doing a bit more work than you need to on this one. You need to have the script execute the same code within the "do" part, i.e. you only need to call your "secret" prompt variable within the "do" brackets. If the user answers the question correctly, then you write that they "know the password, welcome..", i.e. they bust out of the loop.. Below is what I got. Hopefully this helps.
Best,
Dan
var secret;
do {
secret=prompt("What is the password?");
} while (secret!='sesame');
document.write("You know the password. Welcome!");
```
Grace Kelly
33,990 PointsHi micah, I changed your variables a bit e.g the name of the secret variable to password and changed it in the if condition and it works fine now :)
var secret;
var password = "sesame";
do {
secret = prompt("what is the password");
if (secret === password) {
document.write("You know the password. Welcome!");
}
} while ( !secret)
Micah Dunson
34,368 PointsThanks Grace! I knew I was making it harder than it was just couldn't figure out the issue. Makes total sense.
Micah Dunson
34,368 PointsMicah Dunson
34,368 PointsThank you Dan!! You've been a big help. I really appreciate it!