DEV Community

Discussion on: ✔||🤢 Commit or Vomit | nested ternary operator

Collapse
 
cabbage profile image
cab

So yeah, that code right there is garbage. But IMO that's not because of the nested ternary but because of the naming of your operands. And as @lexlohr said the formatting should also in way that it aids the readability. However, I'm uncertain about the prettier formatting is the way I'd do it. Maybe this is a bit more clear?

H = C == 0
  ? null
  : V == r
    ? (g - b) / C
    : V == g
      ? (b - r) / C + 2
      : (r - g) / C + 4;
Enter fullscreen mode Exit fullscreen mode

(aside: my operand naming: condition ? left : right)
Becaus the prettier formatting only works that way if the right operand is always the condition for the next ternary. If one would mix this 'rule' it would be more confusing if the nested ternaries would not be indented.

Nevertheless: Only do it when it serves the readability and use proper names for your operands. Then I'm ok with it. Otherwise 🤮

PS: idgaf if you one calls it conditional or ternary. I cannot remember hearing 'conditional operator' in 15 years in several languages.