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 trialUnsubscribed User
4,479 Points'if' statement only works when 'prompt' is declared as a variable?
I did this as an exercise while revising Javascript Basics.
I tried to generate different alerts depending on responses to prompts.
This code didn't work -
prompt("Do you want to see another prompt?");
if (prompt === "yes") {
alert("That's the way!");
} else {
alert("No problem");
}
This code did work -
var message = prompt("Do you want to see another prompt?");
if (message === "yes") {
alert("That's the way!");
} else {
alert("No problem");
}
I think it has something to do with the declared variable being able to store the response to a command?
Can someone help clarify why I couldn't evaluate the response to a prompt using
if (prompt === "yes")
3 Answers
Steven Parker
231,271 PointsYour first example does not store the response.
In the first example, you call the prompt function, which would display the message, but you don't save the returned response anywhere. Then, you compare the function itself to the word "yes" with the type-sensitive equality operator, which will always be false because prompt is a function and "yes" is a string (plus it still it would never match even with "==").
The second example correctly stores the user's input string in a variable and then tests that variable's content.
Unsubscribed User
4,479 PointsThanks for explaining all the issues so clearly Steven.
Teacher Russell
16,873 PointsI learn as much from reading other people's questions as I do from my own study. Thanks!
Ryan Kistner
723 PointsI completely agree Russel, Thanks for posting this Rory.
I also used the the returned response from my prompt in later code.
var userPrompt = prompt("What is your name?").toLowerCase();
if (userPrompt === 'ryan'){
console.log("Correctly done Ryan");
document.write("Welcome Ryan!");
} else {
(userPrompt !== 'ryan');
console.log("Correctly done " + userPrompt);
document.write("welcome " + userPrompt);
};
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsIn first example , why the "else" part of the program is getting executed? When i run the first example i got "No problem" as the result. I guess i will get nothing as result because as you said , we are comparing function itself with the word "yes".