Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator: bad or good practice? [duplicate]

People also ask

Is using ternary operator good practice?

The ternary operator is a common tool that you'll see a lot in JavaScript code. It can make your code concise but it can also make your code unreadable if you don't use it properly. Try to keep the ternaries simple and readable.

Which is better ternary operator or if-else?

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).

What is the advantage of ternary operator over if-else statement?

The only "advantage" is that you can use the ternary operator in an expression (eg. function arguments), making for terser code. using an if , you'd duplicate the full expression.

Are ternary operators Pythonic?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.


For the sake of readability, I only use a ternary if it fits into one 80-char line.


Good for short tags in templating languages like PHP, e.g:

<form>
<input type='radio' name='gender' value='m' <?=($gender=='m')?"checked":""?>>Male
<input type='radio' name='gender' value='f' <?=($gender=='f')?"checked":""?>>Female
</form>

Good for switches in javascript/jQuery:

var el = $("#something");
$(el).is(':visible') ? $(el).hide("normal") : $(el).fadeIn("normal");

Good for assignment, especially where a particular variable name can take different types:

$var = ($foo->isFoo()) ? 'Success!' : false;

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear. If the intent is not clear, it is best to use a temporary variable with a clear name whose value is assigned using an if-statement, or to use a function with a good name that returns the expected value.


It's something like the for loop. Makes sense for what it's made for but when you try to stick more stuff in it, it becomes unreadable.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!