Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which coding style you use for ternary operator? [closed]

I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:

$value = ( $a == $b )              ? 'true value # 1'             : ( $a == $c )                 ? 'true value # 2'                 : 'false value'; 

Personally which style you use, or find most readable?

Edit: (on when to use ternary-operator)

I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.

like image 434
Imran Avatar asked Oct 28 '08 13:10

Imran


People also ask

How do you code a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Which operator is used as ternary operator?

Remarks. The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool .

Can we use ternary operator in HTML?

Thanks, I was able to do it using the ternary operator. I had the condition ready, just had to replace class with ng-class. ng-class with ternary operator really makes the job simple.

What is the return type of ternary operator?

The return type of ternary expression is bounded to type (char *), yet the expression returns int, hence the program fails. Literally, the program tries to print string at 0th address at runtime.


2 Answers

The ternary operator is generally to be avoided, but this form can be quite readable:

  result = (foo == bar)  ? result1 :            (foo == baz)  ? result2 :            (foo == qux)  ? result3 :            (foo == quux) ? result4 :                             fail_result; 

This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.

like image 194
Simon Howard Avatar answered Oct 16 '22 22:10

Simon Howard


I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.

Only if it can fit on a single line, and it's crystal-clear what it means, I use it:

$value = ($a < 0) ? 'minus' : 'plus'; 
like image 30
Tomalak Avatar answered Oct 16 '22 22:10

Tomalak