DEV Community

Panda Quests
Panda Quests

Posted on

What are reasons not to use the ternary operator?

Top comments (7)

Collapse
 
polilluminato profile image
Alberto Bonacina

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.

Collapse
 
pandaquests profile image
Panda Quests

What about for returning stuff?

Collapse
 
polilluminato profile image
Alberto Bonacina

I don't understand your question. Do you mean the return statement on if/else block or on the assignment?

Thread Thread
 
pandaquests profile image
Panda Quests

On a function. Like this:
myFun() {
return ???
}

Thread Thread
 
polilluminato profile image
Alberto Bonacina

You could use:

return (conditionToCheck ? valueReturn1 : valueReturn2);

Collapse
 
paulnoth profile image
Pavol Pidanič

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

Collapse
 
sebrut profile image
Sebastian Rutofski

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:

if(foo.bar1.baz != foo.bar2?.baz) foo.bar1.baz.reversed() else foo.bar2?.baz.toUpperCase()

Same, but better formatted/split up:

val baz1 = foo.bar1.baz
val baz2 = foo.bar2?.baz
val bazEqual = baz1 == baz2

if (bazEqual) baz2.toUpperCase() else baz1.reversed()