Ternary operators are needed only in languages where if/else
is not an expression. For example, in Java if/else
is a statement so it cannot produce a value, thus the ternary operator. Contrast it with something like Ruby where if/else
is an expression. Now, Ruby also features a C-style ternary operator. Using it can result it more concise code, though some may say at the cost of readability.
One difference between having a ternary conditional operator and if expressions is that the body of an if branch may contain multiple statements and usually the last expression in the block serves as the return value, whereas the ternary operator can only contain a single expression in its branches. The latter limitation may be surpassed by extracting the set of statements into a separate function.
As for pros and cons, I think we should use the most expressive tools we can as long as we don't sacrifice readability. The ternary operator is pretty common across programming languages (or the equivalent if expression), so I say use it whenever it's convenient.