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

Jade Hudson
Jade Hudson
6,859 Points

I can't figure this one out.

This do while loop has me frothing at the mouth. Can somebody tell me what I'm doing wrong here?

Thanks

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

do {
secret = prompt("What is the secret password?"); 
}

if(secret === "sesame"){ 
  correctGuess = true;
}
while (correctGuess = false)    
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

Colin Bell
Colin Bell
29,679 Points

Your if statement is outside of your do statement. Once you move it inside of that, it will work.

Also, once you fix that, it's going to tell you that:

You only need to call the prompt() method once, and only inside the loop

So just set var prompt; on line 1 to declare it as a global variable

You want it as a global variable so that the while condition has access to it, , but don't need to set it to anything until your do statement - which you are doing correctly.

Vicki Corich
Vicki Corich
6,632 Points

I entered, while(secret !== "sesame") and that passed. Would (!"sesame") for a while statement work?

Hi, Vicki Corich:

Can you clarify what context you meant by (!"seasame")? That alone would always return false since a string with a length more than 1 will be interpreted as true & then coerced to a boolean & the opposite of its current interpreted value associated w/ true/false via the !.

Often, developers use !! to safely coerce a value into true or false. The second ! ensures the coercion happens * then a more normalized way of seeing if the value is true or false.