DEV Community

Discussion on: 5 Programming Patterns I Like

Collapse
 
geompse profile image
Geompse

Nested ternaries can be tricky for their operator not having the same priority between programming langages :

a='a',b='b',c='c',d='d',e='e',a?b:c?d:e; // ==='b'
$a='a';$b='b';$c='c';$d='d';$e='e';echo $a?$b:$c?$d:$e; // ==='d'

Also using spaces or multiple lines may mislead the programmer, suggesting priority :

a?b:c ? d : e;
a?b:c
  ?
    d
  :
    e;

To me, it is always better to use parenthesis, on one line of code. If the line goes too long you should use variables (as in pattern 4 "No 'foo' variables") :

const result1 = !conditionA ? "Not A" : (conditionB ? "A & B" : "A");
const result2 = (!conditionA ? "Not A" : conditionB) ? "A & B" : "A";

Still my preference goes to a non nested if/elseif/else blocks (i find it a lot clearer) :

if (!conditionA) {
  result = "Not A";
else if (conditionB) {
  result = "A & B";
} else {
  result = "A";
}