Reputation: 21
I'm a complete beginner trying to make a quick text-based thing with what I learned in one day of Javascript. Why can't this code get past the first IF condition? If I type anything other than "yes" it still says "woohoo!" I've tried else if statements and everything but I can't figure it out.
Thanks for pointing out my mistakes.
var firstName = prompt("What's your first name?");
var lastName = prompt("Ooo I like that. So, what's your last name?");
var answer = prompt(firstName + " " + lastName + ", huh? Wow, I love that name! I'm a little bored right now...so, would you like to play a Choose Your Own Adventure Game?");
if (answer === "yes" || "Yes") {
alert("Woohoo! I haven't played this in a long time. Okay, here goes. Press the OK button to start.");
}
else {
alert("Oh, okay. Well, I'll see you later.");
}
Upvotes: 1
Views: 50
Reputation: 1707
Just correct your if condition,it should be
if (answer || answer.toLowerCase() === "yes") {
//dosomething
}
It will check the answer for both the values ("yes" and "Yes").
Upvotes: 0
Reputation: 25864
The problem is your (answer === "yes" || "Yes")
condition... "Yes"
always evaluates to true
(in Javascript), so you're basically saying 'does answer === "yes" or true'... which is always true. To correct the logic, you should use (answer === "yes" || answer === "Yes")
I'd normalise the output (and check for a response), so that you can just check for one condition...
var firstName = prompt("What's your first name?");
var lastName = prompt("Ooo I like that. So, what's your last name?");
var answer = prompt(firstName + " " + lastName + ", huh? Wow, I love that name! I'm a little bored right now...so, would you like to play a Choose Your Own Adventure Game?");
if (answer && answer.toLowerCase() === "yes") {
alert("Woohoo! I haven't played this in a long time. Okay, here goes. Press the OK button to start.");
}
else {
alert("Oh, okay. Well, I'll see you later.");
}
Upvotes: 2
Reputation: 370729
Non-empty strings (such as the string 'Yes') are always truthy, so if (answer === "yes" || "Yes") {
will always evaluate to if (true)
. If you want to check to see if the answer is either yes
or Yes
, you can put them into an array and use .includes
:
const yesArr = ['yes', 'Yes'];
console.log(yesArr.includes('Yes'));
console.log(yesArr.includes('No'));
Or if the capitalization doesn't matter at all, either convert the string to lower case first and then check:
console.log('YES'.toLowerCase() === 'yes')
Or you might use a case-insensitive regular expression:
console.log(/yes/i.test('YES'))
Upvotes: 0