简体   繁体   中英

Convert if statement to ternary operator

I tried to convert these if statement to ternary:

var eatsPlants = false;
var eatsAnimals = true;

    if(eatsPlants){
      return 'herbivore';
    }else if(eatsAnimals){
      return 'carnivore';
    }else if(eatsPlants && eatsAnimals){
    return 'omnivore';
    }else{
     return undefined;
    }

Here's my solution:

var category = eatsPlants && eatsAnimals ? "omnivore" : "herbivore" : "carnivore" : undefined;

console.log(category);

But this doesnt work and it returns the error missing semicolon.

Any idea how to fix it?

You forgot the other two conditions, and changed the order of checks (which is actually necessary to make it work, though). You'd do either

return (eatsPlants && eatsAnimals
  ? 'omnivore'
  : (eatsPlants
    ? 'herbivore'
    : (eatsAnimals
      ? 'carnivore'
      : undefined)));

or, avoiding the AND operation by nesting,

return (eatsPlants
  ? (eatsAnimals
    ? 'omnivore'
    : 'herbivore')
  : (eatsAnimals
    ? 'carnivore'
    : undefined));

(The parenthesis and indentation are optional, but strongly encouraged for readability, at least one of them).

You should add the remaining if conditions too

var category = eatsPlants && eatsAnimals ? "omnivore" : eatsPlants? "herbivore" : eatsAnimals? "carnivore" : undefined;

console.log(category);

The js snippet shared by you may throw an error as return statement is not inside a function.

Have created one more variable returnResult which will be assinged with new value depending on the condition.

!1 is false & !0 is true, void 0 is undefined

var eatsPlants = !1, eatsAnimals = !0, returnResult = "";
returnResult = eatsPlants ? "herbivore" : eatsAnimals ? "carnivore" : eatsPlants && eatsAnimals ? "omnivore" : void 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM