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.
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.
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 .
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.
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.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With