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 trialShoaib Khan
Front End Web Development Techdegree Graduate 21,177 PointsI need some help in parsing some JavaScript code for this code challenge.
I can't seem to get this code to accept. What am I doing wrong? I have created a test workspace and when I run the code I get prompted for the password and type in "sesame" and then I am prompted again and then I retype the password and then the code will run the while statement and then write to the document. I can't seem to get it to write to the document the first time around. Please help.
var secret = "sesame";
do {
var secret = prompt("What is the secret password?");
if ( secret === "sesame" ) {
document.write("You know the secret password. Welcome.");
}
} while ( secret !== "sesame" )
secret = prompt("What is the secret password?");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
3 Answers
Linas Mackonis
7,071 PointsHi Shoaib,
You write the do while loop like this:
var secret;
do {
secret = prompt("What is the secret password?");
}
while ( secret !== "sesame" );
document.write("You know the secret password. Welcome.");
Linas Mackonis
7,071 PointsYou are re-declaring the secret variable for the second time in the do code block, which you should avoid.
First you declare the variable then you assign the prompt value inside the do code block.
The loop runs the same question until a certain condition is met. In this case secrete not being equal to a 'sesame'. When the word is equal to 'sesame' the loop stops and the code can proceed to the write() function.
Hope that was helpful!
Shoaib Khan
Front End Web Development Techdegree Graduate 21,177 PointsI was able to figure it out!
var secret = "sesame";
do { var password = prompt("What is the secret password?"); if ( secret === password ) { document.write("You know the secret password. Welcome."); } } while ( secret !== password );
Thanks for all the replies!