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 trialshawn007
15,408 PointsNote sure why this will not do the same as the question asked.
while ( secret !== 'sesame'){ var secret = prompt("What is the secret password?"); } document.write("You know the secret password. Welcome.");
while ( secret !== 'sesame'){
var secret = prompt("What is the secret password?");
}
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>
3 Answers
Justin Iezzi
18,199 PointsHey Shawn,
Remember that Javascript is read from top to bottom. Your while loop is checking a condition for a variable that doesn't exist yet, because it's declared inside of the loop, not before it.
You'll also need to prompt the user before the while loop, so that the loop condition has something to check.
Please feel free to ask for further clarification if needed!
shawn007
15,408 PointsJustin,
I'm stuck again. I set a var secret as 'none' so that the while loop sees that secret is not equal to 'sesame'.
Now i get an error saying "Don't use the var
keyword inside the loop. You only need to declare the secret
variable once, at the beginning of the script."
My code:
var secret = 'none'; while ('sesame' !== secret) { var secret = prompt("What is the secret password?"); } document.write("You know the secret password. Welcome.");
Note: I have tested this code and it does work like they asked.
Shawn
Justin Iezzi
18,199 PointsIt will technically work the way you've made it. The issue is that you're declaring the secret variable again, which is bad practice, and deep down can cause some issues.
To save the the computer the extra work, we can write it like this -
// If answer is correct, we'll save some performance by skipping the while loop entirely
var secret = prompt("What is the secret password?");
// Since the secret variable has already been created, we can use that instead of creating another variable called secret
while ('sesame' !== secret) {
secret = prompt("What is the secret password?");
}
document.write("You know the secret password. Welcome.");
shawn007
15,408 PointsJustin,
Thanks for the help! Will keep that in mind about the bad practice you mentioned. Will update my notes on that. Thanks again.
Shawn
Justin Iezzi
18,199 PointsOf course!