javascriptsyntaxcomparisonlogical-operatorsor-operator

How to use the OR operator (`||`, double vertical line) to compare an expression against multiple possible values?


var choice1 = prompt("Enter choice 1");
var choice2 = prompt("Enter choice 2");

if (choice1 === "x" && choice2 === ("a" || "b" || "c")) {
  alert("Good job!");
}

Assume the user input x for choice1 and c for choice 2.

The above is a simple example to highlight my issue. I know it doesn't work but my question is why? Javascript won't compare the multiple || statements within () against choice2. Why not? The logic in my mind is choice2 is the same type and value (===) as "a" or "b" or "c".

The way I got it working was this:

(choice1 === "x" && ((choice2 === "a") || (choice2 === "b") || (choice3 === "c"));

Please help me understand why when using multiple ||'s, you need to explicitly write out each || scenario as opposed to putting a bunch within () as I tried up top. Thanks.


Solution

  • It just doesn't work that way, you can't compare one value against multiple other values using OR, you have to compare each value individually.

    The closest you'll get is using Array.indexOf

    if ( ['a', 'b', 'c'].indexOf(choice2) != -1 )
    

    The reason it doesn't work is because OR and AND checks for a truthy value, so in

    ('a' || 'b' || 'c') // return "a"
    

    a is a truthy value, so the OR never proceeds, it doesn't have to, it already has a truthy value so the expression is true, and you're left with a, the rest is discarded