If you use it to assign a value to a variable obviously yes, it's handy to use; but if you have stuff to do in the if or else block it's non suitable.
In other way: if the code that you have to write stays on one line or you have to do a simple assignement it's useful to use it, otherwise no.
Alberto made a nice and clear explanation. The same would hold for returning stuff - if the code that you have to write stays on one line or you have to do a simple assignment it's useful to use it
The readability can suffer quite a bit if you try to put complex conditions and expressions in a ternary expression. Also, sometimes you're not able to format the expression to improve readability.
Some languages also don't include shorthands for declaring ternary expressions, making them look like improperly formatted if-else statements. (looking at you kotlin!)
In the end it depends on how you actually implement your expression, for example here are to ways to express the same thing.
Top comments (7)
If you use it to assign a value to a variable obviously yes, it's handy to use; but if you have stuff to do in the if or else block it's non suitable.
In other way: if the code that you have to write stays on one line or you have to do a simple assignement it's useful to use it, otherwise no.
What about for returning stuff?
I don't understand your question. Do you mean the return statement on if/else block or on the assignment?
On a function. Like this:
myFun() {
return ???
}
You could use:
return (conditionToCheck ? valueReturn1 : valueReturn2);
Alberto made a nice and clear explanation. The same would hold for returning stuff - if the code that you have to write stays on one line or you have to do a simple assignment it's useful to use it
The readability can suffer quite a bit if you try to put complex conditions and expressions in a ternary expression. Also, sometimes you're not able to format the expression to improve readability.
Some languages also don't include shorthands for declaring ternary expressions, making them look like improperly formatted if-else statements. (looking at you kotlin!)
In the end it depends on how you actually implement your expression, for example here are to ways to express the same thing.
Bad readability:
Same, but better formatted/split up: