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 trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a `do...while` loop

the do while loop is not working

I can not figure out why this is not working.

script.js
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."); 
}
index.html
<!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
Raffael Dettling
32,998 Points

You 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.");

Thank you!

Christopher De Lette
PLUS
Christopher De Lette
Courses Plus Student 7,139 Points

Hi 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!

Thankyou!

Christopher De Lette
PLUS
Christopher De Lette
Courses Plus Student 7,139 Points

You're most certainly welcome Jan! Please close this thread by choosing the best answer and Happy Coding!