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

Raeed Sabree
Raeed Sabree
10,664 Points

add a while loop so that a prompt keeps appearing until the user types :sesame: into the prompt

i know i did something wrong here

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

document.write("You know the secret password. Welcome.");

while (sesame) {

}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>

2 Answers

Hi,

To use a while loop you need a condition and a statement.

while(condition) {
statement
}

For example:

var aVariable = "i am a string";

while(aVariable === "i am a string") {
  // do something
}

This loop will continue to do something as long as the condition is true. i.e as long as the variable 'aVariable' is equal to the string "i am a string".


You could also do the opposite using a slightly different condition, this time using ! which means not:

var aVariable =  "i am a string";

while(aVariable !==  "i am a string") {
  // do something
}

This time the loop will only do something while aVariable is not equal to "i am a string".


Check out while loops and comparison operators

Hope this helps :)

jag
jag
18,266 Points
var secret = prompt("What is the secret password?");



while (secret !== "sesame"){
  secret = prompt("Incorrect, try again.")
}

document.write("You know the secret password. Welcome.");

Sesame is the response they need give. If the response isn't "sesame" then it will loop and you will have to create a new prompt within the while.