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

Teacher Russell
Teacher Russell
16,873 Points

do...while loops?

Getting stuck on every exercise. Getting no studying done. Time to quit Treehouse and hire a teacher:) But one last one...Anyone?

script.js
do  {
   var secret = prompt("What is the secret password?"); 
}
  while ( secret !== "sesame" ) 
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>
Christopher De Lette
Christopher De Lette
Courses Plus Student 7,139 Points

Hi Russell,

You are doing a great job as you have everything correct syntactically setting up the do while loop, however, you are creating a variable inside the loop and with each iteration the compiler will try to create a new variable. Try declaring your variable globally and remove the declaration from your loop.

Take care and happy coding!

2 Answers

Pretty close. If you declare the variable before the loop (var secret;) and add a semicolon after the while condition you should have it correct.

Bummer! You should declare the secret variable before the loop. Otherwise, you re-create that variable each time through the loop.

Though your code executes just fine in the browser, this response to your code is letting you know that your loop is re-declaring the secret variable with each loop iteration. Re-declaring variables (unless you have a specific reason to do so) is considered bad form. And that's why the Code Challenge won't allow it.

The following also executes just fine in the browser and the Code Challenge accepts it as valid:

var secret;

do  {
   secret = prompt("What is the secret password?");
}
  while ( secret !== "sesame" )
document.write("You know the secret password. Welcome.");