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 trialChristiaan Quyn
14,706 PointsWhy can't I set a Variable inside a while loop ?
So I got the challenge right, I'm just a little confused as to why I cant assign var to secret in the while loop, I just happened to take it off and passed the challenge but I'd love if someone could explain to me why I can't do this ? So a variable shouldn't be set in the loop ? By taking var out what does that exactly do ?
Cheers :D
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.");
1 Answer
Daniel Gauthier
15,000 PointsHey Christiaan,
I'm assuming that the question you're asking is that you tried this code:
var secret = prompt("What is the secret password?");
while (secret !== "sesame") {
var secret = prompt("What is the secret password?");
}
document.write("You know the secret password. Welcome.");
& you're wondering why you couldn't use the var keyword in the loop?
If so, the explanation is that you only use the var keyword when you first create the variable.
Since you had already created the variable outside of the loop, you can then set the variable using the assignment operator (the equals sign).
The var keywords simply tells the parser "I'd like to create a new variable", so variables that have already been created can skip this part.
So, the reason the code above didn't pass is because you were telling the parser "I'd like to create a variable named secret." when one had already been created using that name.
For the record, the code would work in a real world application the way you tried it, but it's not the best practice.
Good luck with the course!
Christiaan Quyn
14,706 PointsChristiaan Quyn
14,706 PointsOh .. I get it now .. thank you so much :)