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 A Closer Look At Loop Conditions

Mia Pivirotto
Mia Pivirotto
5,557 Points

Cannot figure out the logistics behind this code challenge, please help.

Ok the question goes "The code in app.js just opens a prompt, asks for a password, and writes to the document. Something is missing. Add a while loop, so that a prompt keeps appearing until the user types "sesame" into the prompt.

I can't figure out how to get this code working?

2 Answers

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

We prompt the user for the secret password, and whatever they put in gets put inside of the secret variable. As long as their answer isn't "sesame", we want to keep prompting them again and again until they get it right, and only then will we tell them "You know the secret password. Welcome.".

The way we do this is with a while loop. The condition of the while loop is that the contents of secret isn't "sesame". We can test if two things are not the same with !==. If they're not the same, this operator will return true, which means our while loop keeps going. Inside the loop, we prompt them again, and put their answer inside secret. The while loop will then test against the contents of secret again, and if the new contents of the secret variable is "sesame", that will mean the condition will be false, and we won't loop anymore and we'll move on to the next bit of code.

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.");
Mia Pivirotto
Mia Pivirotto
5,557 Points

Ok thanks! I was thinking along those lines, the answer just seemed so repetitive having the secret = prompt("What is the secret password?"); line of code twice. Is there not a way to make it more succinct?

Rajeeve Narayanan
Rajeeve Narayanan
3,608 Points

I was getting stuck with this as well. Thanks for the explanation.