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 trialSjoerd Vermeijden
844 PointsWhile loop prompt untill correct answer
I have tried this in a alot of diffrent ways but can not get it to work.
It is the Javascript loops, Arrays > Simplify Repetitive Tasks with Loops > a closer look at loop conditions (2).
Can anyone help me?
var secret = prompt("What is the secret password?");
while (secret === "sesame")
if (secret !== "sesame") {
break;
}
}
document.write("You know the secret password. Welcome.");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
4 Answers
Grace Kelly
33,990 PointsHi Sjoerd, you want to continue with the while loop as long as the password doesn't equal to "sesame", we do this in the following way:
var secret;
while (secret !== "sesame") {
secret = prompt("What is the secret password?");
}
As you can see the !== operator evaluates whether the password is equal to sesame, if it doesn't the user will be asked for the password again. To ask whether the password IS equal to "sesame" we place the following inside the while loop:
if (secret === "sesame") {
break;
}
Notice the === operator? this asks if the password IS equal to "sesame" and if it is we want to break out of the loop.
Hope that helps!!
Sara Hardy
8,650 PointsWhat you want to do is reverse this. While input is NOT equal to "sesame" prompt for password.
So first you'd just declare your variable without a value. Since it's empty, the first time your while loop hits, it will evaluate it as NOT equal to "sesame" and run the loop. Then inside that loop you call the prompt and set the value to your variable that is being checked.
var secret;
while (secret !== "sesame") {
secret = prompt("What is the secret password?");
}
Unsubscribed User
6,144 PointsThink about it, what do you really want to do ?
In a sentence, we could say : "while the answer from the visitor is not equal to 'sesame', keep prompting him".
Then you just have to translate this into code :)
Sjoerd Vermeijden
844 PointsThank!
Sjoerd Vermeijden
844 PointsThank you!