Ardent
Ardent

Reputation: 49

Why doesn't this code work? Javascript if statement, else if statement

This is a javascript code, and I wanted to make it like: if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question." But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question." help!

var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}

Upvotes: 0

Views: 75

Answers (2)

Krzysztof Janiszewski
Krzysztof Janiszewski

Reputation: 3854

Ok, so the problem is in line

if(id || "yes" || "no")

You check whteher the id variable exist or string "yes" exist or string "no" exist. So it is allways true.

If you want to check if string contains some value you can do it either by regular expression (more) or simply by indexOf eg:

var id;

id = prompt("Are you happy?");

if (id == "yes") {

  alert("That's cool.");
  
} else if(id == "no") {

  alert("I'll make you happy.");
  
} else if(id.indexOf('yes') >= 0 || id.indexOf('no') >= 0) {

  alert("Type only yes or no, without any extra texts.");
  
} else {

  alert("you didn't even answer the question.");
  
}

Regards, KJ

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075337

This line:

else if(id || "yes" || "no")

doesn't test whether id has the values "yes" or "no" in it. It tests if id is truthy*, or "yes" is truthy (it is), or "no" is truthy (it is). So the overall condition will always be true, regardless of the value of id.

Since you're using else if, you don't need to check for "yes" or "no" at all at that point — if you got there, you know id doesn't have either of them in it. So just

else if (id)

...will tell you that id has something in it, but it wasn't "yes" or "no" (because you already handled them).


* "truthy" - Coerces to or is treated as true when coerced to boolean or used in a logical operation. It's the other side of "falsy," which coerces to or is treated as false in the same situations. The falsy values in JavaScript are 0, "", null, undefined, NaN, and of course, false. All other values are truthy (including " ", FWIW).

Upvotes: 5

Related Questions