Search code examples
javascriptstringstring-comparisoncomparison-operators

Compare strings with !== in JavaScript


I want to compare two strings introduced by user with prompt.

If I do (bar == "yes" || bar == "no")

it works correctly, but if I use !==

(bar !== "yes" || bar !== "no")

the program return always the

alert("The second value must be \'yes\' or \'no\'");

even when I introduce yes or no as a second value.

do{
    var values = window.prompt("Introduce a title, and \'yes\' o \'no\' separted with a comma.");
    var longValues = values.length;
    var comma = values.indexOf(",");
    var title = values.substr(0,comma);
    var bar = values.substr(comma+1,longValues);
    var longTitle = title.length;

  if (longTitle <3 || longTitle >30){
     alert("The title must be greater than 3 characters and less than 30 characters");
 }
 else if (bar !== "yes" || bar !== "no"){
    alert("The second value must be \'yes\' or \'no\'");
}
 else{
     alert("Correct!");
 }
}while((longTitle <3 || longTitle >30) && (bar !=="yes" || bar !=="no"))

Solution

  • Your condition needs to be AND instead of OR. Change

    if (bar !== "yes" || bar !== "no")
    

    to

    if (bar !== "yes" && bar !== "no")
    

    If you are using OR, you are asking your code if bar is not equal to yes or bar is not equal to no. If value of bar is yes, then first condition is false, but second condition is true, so the result is true. The same is also valid if bar is no - in that case first condition gives true, second condition false, so the result is also true.

    What you want instead is to execute code when bar is not yes and also when bar is not no.