Search code examples
javascriptoperatorsternary

Ternary operators with more than one variable


I have been introduced to the concept of ternary operators, and it's pretty straightforward to understand the notation:

desired_variable = true ? false ? "value1" : "value2";

I could not understand, however, the rational behind adding a second variable, even if I understand the answer. To use a classic example:

var eatsPlants = false;
var eatsAnimals = false;
var category;

category = eatsPlants ? eatsAnimals ? "omnivore" : "herbivore" : eatsAnimals ? "carnivore" : undefined;
console.log(category)

Here, one observation: If I change the order of the variables to the statement below, the function does not work:

category = eatsAnimals ? eatsPlants? "carnivore" : undefined : eatsPlants ? "herbivore" : "omnivore";
console.log(category)

My question: why doesn't the function work when the terms are inverted? And how do I choose the order of the terms when I have two or more variables (and therefore four or more results)?


Solution

  • You can understand by this example.

    x ? ( y ? a : b ) : c
    |
    |________true   ---> y ? a : b
    |
    |________false  ---> c
    
    • first check the value of x if it is true it will run y ? a : b (i have added () just for readability )
    • If it is false it will go to c

    You can simply understand it same as if/else, if i change above code to if/else

    if(x){
      if(y) {
        return a
      } else {
        return b
    } else {
       return c
     }
    }