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

Kit Howlett
Kit Howlett
4,604 Points

Really struggling with this challenge!

Sorry I really can't work out how to get this to work! I thought I understood do loops :(

script.js
/*
var secret = prompt("What is the secret password?");
while ( secret !== "sesame" ) {
  secret = prompt("What is the secret password?");    
}
document.write("You know the secret password. Welcome.");
*/

var secret;

do (secret !== "sesame") {
  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>

2 Answers

Kit Howlett
Kit Howlett
4,604 Points

I worked it out! Got it very wrong initially but after reviewing a do loop I now understand that you don't need to add a condition initially online after 'while ()'.

Is that correct?

Victor Warner
Victor Warner
1,882 Points

if you dont add a condition doenst that just run an infi loop?

Jamie Reardon
Jamie Reardon
Treehouse Project Reviewer

Not sure if I understand your question by "online". If you are referring to a do while loop, the parenthesis after the keyword while is where you place the condition for the loop to run. That condition must be true in order for the do while loop to run more than the first initialized time.

Jamie Reardon
Jamie Reardon
Treehouse Project Reviewer

Victor, if you are referring about a do while loop, you won't have a infinite loop, this is because your code block is run once as the interpreter reads up to the loop, if no condition is met, then the loop is over. Not sure if you will get a syntax error or not as I haven't never supplied a condition.

Jamie Reardon
Jamie Reardon
Treehouse Project Reviewer

An infinite loop is where the test condition never evaluates to false, you need to find a way to break the loop, either being through evaluating the condition to false or using a keyword such as break to end the loop.

Jamie Reardon
Jamie Reardon
Treehouse Project Reviewer

A do while loop runs at least once, due to the condition being read after the code block. After the do keyword follows a pair of curly braces which will hold the block of code you want to execute at least once and while the condition is true.

After that is the while keyword followed by the condition of the loop inside a pair of parenthesis.

Well done on figuring it out!