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

kingdavid igbayilola
kingdavid igbayilola
8,678 Points

confusing do...while loop

i keep on getting syntax error and can't point out where is coming from.

script.js
 var secret = prompt("What is the secret password?");
var password = "sesame";

do(secret === password){
  document.write("You know the secret password. Welcome.");
}
while ( secret !== "sesame" ){
  secret = prompt("What is the secret password?");    
}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

2 Answers

Antonio De Rose
Antonio De Rose
20,885 Points

the below is the do while format, can you get some help from the below, and give a shot.

var text = "";
var i = 0;
do {
    text += "The number is " + i;
    i++;
}
while (i < 5);
Brandon Spangler
Brandon Spangler
8,756 Points

The syntax of your do-while loop will look like this:

do{
//The code in here will execute once before the while condition is checked.
//It will run, possibly forever, until your while condition evaluates to false
  }while(this is true)

The purpose to use a do-while loop is to make sure the inside of your loop runs once before the condition is checked. In this example we want to ask the user for a password once before we check their input against the answer, then if they're wrong, we want to execute the loop, possibly forever, until they get the password correct So I'll clean some stuff up for you but I'll leave it to you to get the answer

var secret;
var password = "sesame"; //only need to declare this once

do{
  //something that we want to do possibly forever
 }while ( //condition we want to check )
//after the above condition evaluates to true we'll break out of the loop and execute this line we probably want to tell them they guessed the word correctly here