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 trialJibril Abdul
16,535 PointsDon't understand this code challenge.
Here is my original code.
var secret = prompt("What is the secret password?");
do {
if (secret !== "sesame") {
secret = prompt("What is the secret password?");
}
} while ( secret !== "sesame" );
document.write("You know the secret password. Welcome.");
Okay, so about 20 minutes of trying I finally figured it out, but what I don't get is why I cannot replace
if (secret !== "sesame") {
secret = prompt("What is the secret password?");
}
with
if (secret !== "sesame") {
secret;
}
Why is there a problem if the prompt is stored in the variable secret, especially since the variable is a global one (I think), and not one that was first defined within the do loop?
3 Answers
Nathan Smutz
9,492 PointsIn this case, prompt
isn't stored in the variable. The particular thing to look at here are the parentheses in prompt("What is the secret password?")
. Parentheses following a function cause Javascript to "call" the function. This causes the function to do something then return a value. In this case the prompt()
function prints the stuff in the parentheses to the screen and returns a string of whatever you typed. In the case of this code, secret
was there to catch the string that prompt(...)
spit out.
So when we ran:
secret = prompt("What is the secret password?");
all secret got wast the string you typed.
In this case:
if (secret !== "sesame") {
secret;
}
then secret;
just holding the last string you typed doesn't really do anything.
Matthew Smart
5,084 PointsThe variable secret is of type "string", and in the original solution, you are assigning what the user types at the prompt to the variable. "secret" does not equal "prompt('What is the secret password?"), but is assigned the return value of that prompt. "prompt" is a function which returns a string. If you simply type "secret;", you are not telling it to do anything because it is simply a string variable. The problem is that "=" does not mean "equal" here but means "is assigned the value of".
Jibril Abdul
16,535 PointsAha! I get it! I get it! Thank you very much Matthew Smart and Nathan Smutz .