DEV Community

What do you think about the ternary operator?

Shreyas Minocha on August 05, 2018

The ternary operator has a reputation of reducing readability. However, in the right hands, it may result in less duplication. Do you think it's...
Collapse
 
idanarye profile image
Idan Arye

Proper formatting goes a long way at improving readability:

variable = 
    condition1 ? expression1 :
    condition2 ? expression2 :
    condition3 ? expression3 :
    condition4 ? expression4 :
    default_expression;
Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

I'd tend to just method extract this, and use explicit return statements inside plain if-statements.

At least in part, that's because the conditions will rarely be as brief (when they are thus numerous).

Collapse
 
martingbrown profile image
Martin G. Brown

I tend to go a bit further and indent the two expressions:

return
    condition ?
        trueExpression :
        falseExpression;
Collapse
 
shreyasminocha profile image
Shreyas Minocha

Interesting take.

Collapse
 
gcugreyarea profile image
Barry Robinson • Edited

Most modern compilers are smart enough to optimise control statements. It is more readable than it otherwise would be, but why do it in the first place?

Collapse
 
lorenmcclaflin profile image
Loren McClaflin

Wow, Idan, I love your formatting. I’ve not seen a ternary formatted this way, and it really does improve readability!
Thanks for the great tip!

Collapse
 
bgadrian profile image
Adrian B.G.

I feel the same as other "syntax sugar cool" things, when used correctly it improves your code, but most of the time it's going to be over used. I've seen some horrors using the ternary operator you would not believe.


what = (f() ? (g() && x ? a + d : b ) : c)

I used it when dealing with simple, 1 word condition and values.

As a Go newbie I don't miss it, having so few language constructs and operators it is very relieving, you need a condition you use if, simple and efficient. All your peers will do the same, everyone understands it, and it is harder to screw it up.

Collapse
 
shreyasminocha profile image
Shreyas Minocha • Edited

I agree. I've seen it used in some perfectly legitimate ways such as in JSVerbalExpressions.

    startOfLine(enable = true) {
        this._prefixes = enable ? '^' : '';
        return this.add();
    }

    endOfLine(enable = true) {
        this._suffixes = enable ? '$' : '';
        return this.add();
    }

This pattern is repeated throughout the library. Using if-else here would be painful, but it'd be manageable. At least one wouldn't have to deal with the code like you described. Why people would write code of that sort (except for codegolf) is beyond me.

Collapse
 
bgadrian profile image
Adrian B.G.

Why people would write code of that sort (except for codegolf) is beyond me.

The most common reason I saw (is not specific to this problem) was when a dev had to add some new logic, instead of refactoring the ternary expression into an if, switch or separate to functions, or objects or whatever added the new complexity in place.

The reasons why that happened were various, excuses like "I was in a hurry", "I didn't had the time to understand the code" and so on were common.

Fear of refactoring is a common problem in projects without tests and/or devs without the desire to write good code, or just insane release schedule, you know, common problems.

Collapse
 
qm3ster profile image
Mihail Malo • Edited
// WHY NOT THIS?
startOfLine(enable = true) {
    this._prefixes = (enable && '^') || ''
    return this.add()
}

// OR EVEN THIS?
endOfLine(enable = true) {
    return(this._suffixes = (enable && '$') || '', this.add.bind(this))()
    //    ^ look mom, no space after `return`                          ^
    //                                                                 |
    //             note the artisanal external position of call parens |
}
Collapse
 
fxedel profile image
Felix Edelmann

I actually like the Kotlin syntax that uses the if/else keywords instead of ?/:

val max = if (a > b) a else b 

It's much more readable than the JS syntax.

However, I often use ternary operators in both languages as they are just quick to write und don't mess up the code with an if/else clause.

Collapse
 
nektro profile image
Meghan (she/her)

Iirc if you surround the if/else statement in parentheses then it is valid in JavaScript as well and will assign the appropriate value to the variable

Collapse
 
z3ta profile image
Z3TA

Can you post an example ? I only get syntax error :/

Collapse
 
_andys8 profile image
Andy

Totally wrong. Statement vs expression. Assignment without mutation.

Collapse
 
shreyasminocha profile image
Shreyas Minocha

That's interesting. I didn't know some languages did it that way.

Collapse
 
kip13 profile image
kip • Edited

This is valid in all languages where if else are an expression instead of statement: Python, Rust, Scala, Kotlin, Haskell,F#....

Collapse
 
t4rzsan profile image
Jakob Christensen

F# does it too.

Collapse
 
nimmo profile image
Nimmo

I'm a big fan of ternaries in JS, because IMO expressions are better than statements for reducing cognitive load, which is generally my primary goal when coding.

However, I find that my personal favourite formatting for ternaries is:

condition
  ? valueIfTrue
  : valueIfFalse;

To be clear though, I do believe that if/else is better for readability (especially for less experienced developers), and I prefer languages which only have expressions (and consequently their if/elses are expressions too). But for languages that aren't as nice as that, I always prefer ternaries for assignments.

Collapse
 
hudsonburgess7 profile image
Hudson Burgess

I think the ternary operator actually encourages readability.

In my experience, the only time ternary syntax reduces readability is if you have too much logic jammed inside a conditional. And if that's the case, the normal if / else syntax wouldn't make things much clearer.

In other words, the ternary operator just "amplifies" how (un)readable the conditional logic is to begin with. Does that make sense?

Collapse
 
nathanverrilli profile image
nathanverrilli

I fail to see the huge fuss. I like the ternary operator, as it renders quick this-or-that-depending expressions easy and fast. Yes, it can be misused. Of course, I still use GOTO for forward error handling in device drivers. Nowhere else, but the legibility increase over nesting a gagzillion IF statements is significant.

I'm for it, because ...
(A) There are a number of good use cases
(B) Stupid coders code stupid regardless of tools. Restricting
everyone else isn't going to make their code better, but it
does make our code worse.

Collapse
 
shreyasminocha profile image
Shreyas Minocha

Stupid coders code stupid regardless of tools

Good point :)

Collapse
 
de_maric profile image
Dejan Maric

Beautifully said :)

Collapse
 
timsev profile image
Tim Severien

I use the ternary operator a lot. I strongly believe it should be used with caution. Most of the time, I start with regular if-statements and reduce it to a ternary operator if I deem the condition and expressions simple enough, even though I realise that is extremely subjective. I never nest ternary operators.

value < threshold ? value : otherValue;

object.someState || object.someOtherState
  ? object.child.doSomething()
  : object.otherChild.doSomethingElse();
Collapse
 
lexlohr profile image
Alex Lohr

In it's simple use, the ternary operator is rather helping than hindering the reading flow, as illustrated by the example:

// w/o ternary operator:
let result;
if (condition) {
  result = CONDITION_MET;
} else {
  result = CONDITION_NOT_MET;
}

// w/ ternary operator:
const result = condition ? CONDITION_MET : CONDITION_NOT_MET;

However, in golfed or minified code, one usually finds abominable abuses of the ternary operator within already complicated statements that reduce readability. Only use them there, never the code you work on.

Collapse
 
courier10pt profile image
Bob van Hoove • Edited

Nitpick: It's a ternary operator known as the conditional operator. For instance in javascript:

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

(ref: MDN Web docs : Conditional (ternary) Operator

I use it quite often. I'm a fan of the formatting style that Nimmo proposes, using a newline for the ? part and another newline for the : such that I don't have to scroll sideways.

Collapse
 
shreyasminocha profile image
Shreyas Minocha

Yeah. Thanks for pointing that out.

Collapse
 
jdsteinhauser profile image
Jason Steinhauser

I tend to use the conditional operator mostly with one-line functions or properties. The idiomatic syntax is a lot easier in C# (my most used language) for one-line functions using the conditional operator.

New Hotness:

int Max(int a, int b) => a > b ? a : b;

Old and Busted:

int Max(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}
Collapse
 
deceze profile image
David Zentgraf

Everything can be written in multiple different ways. The Best Way™ to write something depends on what it is you're trying to write. Sometimes it's much more readable to write a ternary expression, and sometimes it's much more readable to write that same code in an if, and sometimes in a switch, and sometimes using a dictionary or whatever other idiom your language of choice offers. The important thing is to (re-)write code in the most readable way whenever you touch it. There are no hard and fast rules. A piece of code may start out as a ternary expression, but when added to must be rewritten into something else to remain readable. Things become unreadable when you leave something as is (e.g. as a ternary expression) while adding to it because you don't feel like rewriting it.

Collapse
 
shreyasminocha profile image
Shreyas Minocha

Very true.

Collapse
 
jvarness profile image
Jake Varness

Absolutely love it for it's simplicity and how widely it's been implemented in almost every programming language.

But I absolutely cannot stand it when someone does something like this:

return expressionThatReturnsBoolean() ? true : false;

or this:

return !expressionThatReturnsBoolean() ? true : false;

or any variation of taking an expression that returns a boolean and immediately transforming that boolean with a ternary operator to return a boolean.

I've had many people tell me that this improves the "readability" of the statement, but I strongly disagree. I think all it does is add redundancy to the code and add more complexity with little benefit.

Collapse
 
shreyasminocha profile image
Shreyas Minocha • Edited

I agree with you on return expressionThatReturnsBoolean() ? true : false;. Readability can be subjective though ¯\(ツ)/¯.

Collapse
 
jvarness profile image
Jake Varness • Edited

Readability is subjective, but I would say that when your code reads: if true return true, if false return false... I mean you might as well be writing:

if (expressionThatReturnsBoolean() == true) {
  return true;
}
else {
  return false;
}
Thread Thread
 
shreyasminocha profile image
Shreyas Minocha

Perhaps.

Readability is also contextual. I might do similar things in two different ways depending on how readable it would be over there. Doing it your way might be my preference, but sometimes I'll find myself using a ternary for the same.

Collapse
 
pkristiancz profile image
Patrik Kristian

I like ternaries very much. Sometimes when options are longer i go with folowing formating:

$foo = $isFooConsideredBar
    ? $fooIsIndeedConsideredBar
    : $fooIsNoWayCknsideredBar
;
Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited

I love ternaries and think they improve readability but:

  1. I keep strict ESLint rules for code standardization, which ensures ternary operations are formatted in a readable way and
  2. my background is in mathematics, so everything and anything is better than nested ifs in Excel. I'll never see anything else as unreadable after some of those messes I've had to read and create in order to finish a class.
Collapse
 
soerenfandrich profile image
Sören Fandrich • Edited

It's like an if-else in Scala, that returns a value. Nothing wrong with that, it's just that ? : is not intuitive to read. But if used carefully, and not just showing off how smart you are ;-) it can actually improve readability.

Collapse
 
cathodion profile image
Dustin King

I think languages need it. I think it's necessary for making the code flow in the same order as how things work in your mind. But I don't think it improves readability except in Lisp (because it's just a regular If statement).

In Lisp (It's been a few years, so forgive me any syntax errors) it's:

(setq variable (if condition something somethingElse))

In Python what it actually is is:

variable = something if condition else somethingElse

Whereas I'd like it to be:

variable = if condition something else somethingElse
Collapse
 
twigman08 profile image
Chad Smith

As with everything in programming it has its place and can be used, as long as it is used right.

In languages where if's are only statements and not expressions then it becomes helpful. Of course don't abuse it. If you find yourself needing to write nested ternary operators then I would start thinking about refactoring that to a switch-case (or if-else if it's a string and the language doesn't support switch-case on string's).

Collapse
 
mah-rye-kuh profile image
Marijke Luttekes

A single ternary is fine, as long as you don't write down a long line of complicated logic. It's especially joy when providing default values for variables that may or may not have a value.

Screw multi-ternaries though. Even when aligned properly I hate reading those and figuring out what they do exactly.

Collapse
 
kayis profile image
K

Sadly it's needed in all the languages that don't have if-expressions.

But I have the feeling, newer language designs include if-expressions instead of if-statements more often.

Collapse
 
sake_92 profile image
Sakib Hadžiavdić • Edited

I prefer if expressions (e.g. in Scala):
val res = if(a) 1 else if(b) 2 else 3
It just feels more natural and concise

Collapse
 
vikkio88 profile image
Vincenzo

every time someone uses an else instead of a ternary a cute cat dies somewhere.

Collapse
 
lorenmcclaflin profile image
Loren McClaflin

With only ~1yr. JS experience, I love the ternary operator.
Sure, it took some practice, especially with those “...or else, or else, or else” statements, but let’s face it, the example BG Adrian uses is diffucult to follow long-hand, as well.
The ternary operator offers us a succinct, efficient alternative to if/then/else blocks.
But- again using BG’s example, I/we can take this as a reminder to reflect on our code, and document - or refactor, to maximize its readability.

Collapse
 
hector6872 profile image
Hector de Isidro

I actually miss it in Kotlin.

Collapse
 
bossajie profile image
Boss A • Edited

for me, ternary operator is only good for one expression only.

Collapse
 
mudlabs profile image
Sam

Love it, use it all the time.

Collapse
 
drewknab profile image
Drew Knab

I like them quite a bit. Like everyone else has said, they're pretty easy to abuse or sneak into a place they don't belong.

Collapse
 
moopet profile image
Ben Sinclair

I agree with the others here that they're nice for simple conditions but should be used sparingly. They're particularly good in simple return statements.

Collapse
 
adekoder profile image
adekoder

I love to use them, a way for me to avoid "If ... else" statement when I want to do one-liner

Collapse
 
g_pechorin profile image
I R Peter

I miss being able to write it in Scala, I don't miss reading it in Scala