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 trialJan Rynerson
8,502 Pointsthe do while loop is not working
I can not figure out why this is not working.
var secret = prompt("What is the secret password?");
do{ if(secret!=="sesame"){ secret = prompt("What is the secret password?");} }while ( secret === "sesame" ) {
secret=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>
3 Answers
Raffael Dettling
32,999 PointsYou overthinked it. First make your code more readable it makes it a lot easier. Second you assigned the variable secret 3 times you only declare it at the beginning and assign it inside the do while loop and that only when the 2 strings donΒ΄t match
var secret;
do
{
secret = prompt("What is the secret password?");
}while( secret !== "sesame" )
document.write("You know the secret password. Welcome.");
Christopher De Lette
Courses Plus Student 7,139 PointsHi Jan,
Remember a do while loop is best used for running a code block at least once then evaluating a condition. I'll try best to explain in the following code snippet:
var secret; //declare variable to use inside the loop
do {
secret = prompt("What is the secret password?'); //run this block of code at least once
}
while(secret !== "sesame"); //Then test the condition for true/false and if false rerun the code block
document.write("You know the secret password. Welcome!"); //when the condition is true break out of the do-while loop and run this print statement.
Hope this helps and the explanations are enough to learn from.
Take care and Happy Coding!
Jan Rynerson
8,502 PointsThankyou!
Christopher De Lette
Courses Plus Student 7,139 PointsYou're most certainly welcome Jan! Please close this thread by choosing the best answer and Happy Coding!
Jan Rynerson
8,502 PointsJan Rynerson
8,502 PointsThank you!