<p>There are some languages that support ternary operator. There are Python, C, JavaScript, PHP.</p>
<p>In languages like C and JavaScript, the syntax is like this:</p>
<pre class="lang-c prettyprint-override"><code>condition ? do_true : do_false
</code></pre>
<p>Python has another form:</p>
<pre class="lang-python prettyprint-override"><code>do_true if condition else do_false
</code></pre>
<p>But some languages did not support ternary operator, like Go.</p>
<p>So, what are the pros and cons of it?</p>

<operators><conditional>
What are pros/cons of ternary conditional operators?
CC BY-SA 4.0
2023-06-23T09:51:05.397Z
It is a crime against humanity not to allow a ternary operator in a language with separate statements and expressions. Just imagine not having it in, say, Verilog, it will make combinatorial MUXes really atrocious to ezpress  Of all Golang shortcomings this one is among the most damaging.
SK-logic
CC BY-SA 4.0
2023-06-23T14:15:36.367Z
Related: [What are the syntax options for implementing a ternary "if" operator?](https://languagedesign.stackexchange.com/q/78/13)
The Thonnu
CC BY-SA 4.0
2023-06-28T08:59:49.950Z
I asked a similar question a while ago: [What are some caveats to be careful about when implementing the `?:` (ternary conditional) operator?](https://langdev.stackexchange.com/questions/1469/what-are-some-caveats-to-be-careful-about-when-implementing-the-ternary-co)
FlatAssembler
<p><strong>Pros:</strong></p>
<p>It's an expression, and in languages with distinction between expressions and statements it's crucial to have a selection operator available as an expression.  Ternary operator is not necessarily the best syntax though, as the other answers highlighted how convoluted it can become with very little effort. A good alternative is an <code>if-then-else</code> available as an expression and not just statement.</p>
<p><strong>Cons:</strong></p>
<p>It's introducing control flow into expressions, just like logic operators in many languages. When side effects are possible, it's making expressions less visually obvious to follow.</p>
<p>The C-style syntax of <code>C?T:F</code> often leads to convoluted and error-prone code.</p>

CC BY-SA 4.0
2023-06-23T10:30:46.710Z
2023-06-23T10:30:46.710Z
SK-logic
<p>There is a very specific pitfall with ternary operators in statically typed languages which allow type coercions, like Java. Programmers like to refactor code like this to avoid repetition:</p>
<pre class="lang-java prettyprint-override"><code>if(condition) {
    System.out.println(3);
} else {
    System.out.println(4.5);
}
</code></pre>
<p>This can almost be rewritten as:</p>
<pre class="lang-java prettyprint-override"><code>System.out.println(condition ? 3 : 4.5);
</code></pre>
<p>Unfortunately, the two are not equivalent, as the first version prints <code>3</code> when the condition is true, whereas the second version prints <code>3.0</code> because the ternary expression needs to have a static type, so it's <code>double</code>. In general with overloaded methods this can cause arbitrarily different behaviour, though it only rarely makes a difference; I only came across this once when writing an interpreter in Java, where a method like this had a bug because I was too eager to simplify it:</p>
<pre class="lang-java prettyprint-override"><code>Object getDefaultValue(Type t) {
    if(t == Type.DOUBLE) {
        return 0.0;
    } else {
        return 0;
    }
}
</code></pre>
<p>The refactored version unconditionally returns a boxed value of <code>0.0</code> as a <code>Double</code>, because <code>... ? 0.0 : 0</code> coerces to <code>double</code> before the result is coerced to <code>Object</code>.</p>
<p>It's genuinely rare for this refactoring to cause a significant problem in code, so this isn't really an argument against having the ternary operator in your language. But generally no programmer ever wants two type conversions in a row (here, <code>0</code> gets coerced to <code>double</code> then <code>Object</code>) without making both conversions explicit, so it's something to be careful of. (Perhaps there should be a warning for serial implicit type conversions.)</p>

CC BY-SA 4.0
2023-06-25T15:14:57.540Z
2023-06-25T15:14:57.540Z
kaya3
CC BY-SA 4.0
2023-06-27T17:26:01.393Z
This kind of problem is caused by type coercions as well as the ternary operator, not the ternary operator alone
CoffeeTableEspresso
CC BY-SA 4.0
2023-06-27T17:59:32.803Z
@CoffeeTableEspresso Indeed, but for ergonomic reasons you do generally want type coercion to be part of the ternary operator's semantics.
kaya3
<h3>Con: One more darned thing to remember</h3>
<p>The ternary syntax is very different from everything else, and requires somewhat complex additions to the precedence table.</p>

CC BY-SA 4.0
2023-06-23T10:09:03.960Z
2023-06-23T10:09:03.960Z
Adám
CC BY-SA 4.0
2023-06-24T20:27:13.460Z
The thing about C-style conditional expressions is that they _aren’t_ much different from conditional statements—nor other ternary operators like assignment—yet they’re _seen_ very differently, so it becomes an important usability-design question. `if (a) b else c` starts with two more tokens `if (` compared to `a ? b : c`, and `if` and `else` are better mnemonics than `?` and (especially) `:`. Tuning the amount of such redundancy is one of the few objective ways of improving readability and reducing clerical errors. Otherwise, they have the same form, associativity, and relative precedence.
Jon Purdy
<h1>Con: Can lead to unreadable code</h1>
<p>The syntax of <code>?:</code> is pretty unintuitive. Python's <code>X if Y else Z</code> is slightly better. However, this problem becomes worse if many such if-else expressions are nested. For example, <code>(a) ? (b ? c : d) : (e ? f : g)</code> or even the following where it is easy to see what the code does but may be difficult to reason about how it does it:</p>
<pre class="lang-java prettyprint-override"><code>String result = a ? &quot;A&quot; :
                b ? &quot;B&quot; :
                c ? &quot;C&quot; :
                d ? &quot;D&quot; :
                e ? &quot;E&quot; :
                f ? &quot;F&quot; :
                g ? &quot;G&quot; :
                h ? &quot;H&quot; :
                &quot;I&quot;;
</code></pre>
<p>Though these examples are contrived, they show how ternary operators can lead to unwieldy code pretty quickly. Ternary operators are good for short conditional expressions; for larger conditions, if-else statements are better.</p>

CC BY-SA 4.0
2023-06-23T09:35:23.000Z
2023-06-23T09:41:53.627Z
2023-06-23T09:41:53.627Z
FireTheLost
CC BY-SA 4.0
2023-06-23T10:17:56.280Z
The right alternative to a ternary expression would have been an `if-then-else` *expression*. Statement cannot replace expression as statements in most languages cannot be used in the same place as expressions.
SK-logic
CC BY-SA 4.0
2023-06-27T17:24:49.850Z
@SK-logic an `if-then-else` expression is just a ternary operator with different syntax.
CoffeeTableEspresso
CC BY-SA 4.0
2023-06-27T17:27:08.620Z
@CoffeeTableEspresso it's exactly the `C?T:F` syntax that people have problems with. A more verbose syntax removes pretty much all the criticism of ternary expressions.
SK-logic
<p><code>If</code> statement duplicates the part specifying what to do with the conditionally selected value:</p>
<pre><code>if (condition) {
   use_value_now(alpha, beta, 0);
} else { 
   use_value_now(alpha, beta, 1);
}
</code></pre>
<p>It may be OK when the selected value is just assigned to the variable, but for the function call as in this example it almost looks like a dedicated variable should be defined for it. Then it is not so clear how (and if) this variable should be initialized when declared. Curly brackets (or they analogs in other languages) are also now mostly a requirement for the good coding style.</p>
<p>Compare this with</p>
<pre><code>use_value_now(alpha, beta, condition ? 0 : 1);
</code></pre>

CC BY-SA 4.0
2023-06-30T16:52:35.540Z
2023-06-30T16:52:35.540Z
Audrius Meškauskas
CC BY-SA 4.0
2023-06-30T17:49:38.390Z
This isn't necessarily true, e.g. `let gamma; if (condition) { gamma = 0 } else { gamma = 1 }; use_value_now(alpha, beta, gamma);`.
Bbrk24
CC BY-SA 4.0
2023-06-30T20:07:40.793Z
It is how you write. But does not look very short.
Audrius Meškauskas
<h2>Recommendation:</h2>
<p>For expressions, provide the &quot;same&quot; set of conditional constructs that you provide for statements, and for readability, use similar syntax constructs.</p>
<p>The ternary operator's semantics match the if-then-else statement, but its syntax is very different - the operator uses special characters, the if-then-else statement uses readable keywords.</p>
<p>Typically, your language might also provide a switch-case statement, so you should also include a switch-case expression syntax.</p>
<p>Or you might even go one step further: make everything an expression, meaning that even &quot;statements&quot; return something. Then the if-then-else &quot;statement&quot; immediately replaces the ternary operator, without the need to learn two different syntaxes.</p>
<h2>Rationale:</h2>
<p>Expressions that evaluate differently based on some condition are a very intuitive concept. See e.g. <a href="https://en.wikipedia.org/wiki/Absolute_value#Real_numbers" rel="nofollow noreferrer">Absolute Value</a>, it uses an expression with two cases, and we all immediately understand what that means.</p>
<p>The main problem I see with the ternary operator is its syntax. It comes from the C language and follows the typical C cryptic style (is there any special character that we didn't use yet?).</p>

CC BY-SA 4.0
2023-06-28T08:12:11.180Z
2023-06-28T08:12:11.180Z
Ralf Kleberhoff
<h1>Pro:It’s more consice</h1>
<p>This pretty much speaks for itself. Makes life considerably easier and more optimized.</p>

CC BY-SA 4.0
2023-06-23T17:02:16.033Z
2023-06-23T17:02:16.033Z
Starship
<p>Ternary operators are needed only in languages where <code>if/else</code> is not an expression. For example, in Java <code>if/else</code> is a statement so it cannot produce a value, thus the ternary operator. Contrast it with something like Ruby where <code>if/else</code> 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.</p>
<p>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.</p>
<p>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.</p>

CC BY-SA 4.0
2023-06-28T19:38:00.470Z
2023-06-28T19:38:00.470Z
Alexander Goussas
<h2>Pro: Readability</h2>
<p>While plenty of people talk about the readability problems with misused ternary operators, there are also situations where using a full <code>if</code>/<code>else</code> would be annoyingly bulky, spreading a simple statement across five lines, and significantly reducing readability. Here are some sample statements pulled from a project I'm working on:</p>
<pre><code>bg_2d.fillStyle = is_in_bounds(x, y) ? grid_colors[x][y] : &quot;#ffffff&quot;;
</code></pre>
<pre><code>const diagonal_slowdown = is_diagonal() ? Math.SQRT2 : 1;
</code></pre>
<pre><code>const color = (team == &quot;red&quot;) ? &quot;#ff0000&quot; : &quot;#0000ff&quot;;
</code></pre>
<p>When you have a simple situation where you have two things to pick from based on a condition, which happens <em>all the time</em>, ternary is perfect. Having a short syntax for ternary massively improves readability in these situations.</p>

CC BY-SA 4.0
2023-06-23T13:23:15.133Z
2023-06-23T13:23:15.133Z
rydwolf
# What are pros/cons of ternary conditional operators?
Posted by: username_0 on 2023-06-23
There are some languages that support ternary operator. There are Python, C, JavaScript, PHP.
In languages like C and JavaScript, the syntax is like this:
condition ? do_true : do_false

Python has another form:
do_true if condition else do_false

But some languages did not support ternary operator, like Go.
So, what are the pros and cons of it?
**Tags:** operators conditional
> **Comments:**
> **username_1**: It is a crime against humanity not to allow a ternary operator in a language with separate statements and expressions. Just imagine not having it in, say, Verilog, it will make combinatorial MUXes really atrocious to ezpress  Of all Golang shortcomings this one is among the most damaging.  
> **username_2**: Related: [What are the syntax options for implementing a ternary "if" operator?](https://languagedesign.stackexchange.com/q/78/13)  
> **username_3**: I asked a similar question a while ago: [What are some caveats to be careful about when implementing the `?:` (ternary conditional) operator?](https://langdev.stackexchange.com/questions/1469/what-are-some-caveats-to-be-careful-about-when-implementing-the-ternary-co)  
---
## 9 answers
### Answer by username_14 on 2023-06-23. Score: 11
Pro: Readability
While plenty of people talk about the readability problems with misused ternary operators, there are also situations where using a full if/else would be annoyingly bulky, spreading a simple statement across five lines, and significantly reducing readability. Here are some sample statements pulled from a project I'm working on:
bg_2d.fillStyle = is_in_bounds(x, y) ? grid_colors[x][y] : "#ffffff";

const diagonal_slowdown = is_diagonal() ? Math.SQRT2 : 1;

const color = (team == "red") ? "#ff0000" : "#0000ff";

When you have a simple situation where you have two things to pick from based on a condition, which happens all the time, ternary is perfect. Having a short syntax for ternary massively improves readability in these situations.
---
### Answer by username_1 on 2023-06-23. Score: 6
**Pros:**

It's an expression, and in languages with distinction between expressions and statements it's crucial to have a selection operator available as an expression. Ternary operator is not necessarily the best syntax though, as the other answers highlighted how convoluted it can become with very little effort. A good alternative is an `if-then-else` available as an expression and not just statement.

**Cons:**

It's introducing control flow into expressions, just like logic operators in many languages. When side effects are possible, it's making expressions less visually obvious to follow.

The C-style syntax of `C?T:F` often leads to convoluted and error-prone code.
---
### Answer by username_4 on 2023-06-25. Score: 5
There is a very specific pitfall with ternary operators in statically typed languages which allow type coercions, like Java. Programmers like to refactor code like this to avoid repetition:
if(condition) {
    System.out.println(3);
} else {
    System.out.println(4.5);
}

This can almost be rewritten as:
System.out.println(condition ? 3 : 4.5);

Unfortunately, the two are not equivalent, as the first version prints 3 when the condition is true, whereas the second version prints 3.0 because the ternary expression needs to have a static type, so it's double. In general with overloaded methods this can cause arbitrarily different behaviour, though it only rarely makes a difference; I only came across this once when writing an interpreter in Java, where a method like this had a bug because I was too eager to simplify it:
Object getDefaultValue(Type t) {
    if(t == Type.DOUBLE) {
        return 0.0;
    } else {
        return 0;
    }
}

The refactored version unconditionally returns a boxed value of 0.0 as a Double, because ... ? 0.0 : 0 coerces to double before the result is coerced to Object.
It's genuinely rare for this refactoring to cause a significant problem in code, so this isn't really an argument against having the ternary operator in your language. But generally no programmer ever wants two type conversions in a row (here, 0 gets coerced to double then Object) without making both conversions explicit, so it's something to be careful of. (Perhaps there should be a warning for serial implicit type conversions.)
> **Comments:**
> **username_5** (2023-06-27): This kind of problem is caused by type coercions as well as the ternary operator, not the ternary operator alone  
> **username_4** (2023-06-27): @CoffeeTableEspresso Indeed, but for ergonomic reasons you do generally want type coercion to be part of the ternary operator's semantics.  
---
### Answer by username_6 on 2023-06-23. Score: 5
### Con: One more darned thing to remember

The ternary syntax is very different from everything else, and requires somewhat complex additions to the precedence table.
> **Comments:**
> **username_7** (2023-06-24): The thing about C-style conditional expressions is that they _aren’t_ much different from conditional statements—nor other ternary operators like assignment—yet they’re _seen_ very differently, so it becomes an important usability-design question. `if (a) b else c` starts with two more tokens `if (` compared to `a ? b : c`, and `if` and `else` are better mnemonics than `?` and (especially) `:`. Tuning the amount of such redundancy is one of the few objective ways of improving readability and reducing clerical errors. Otherwise, they have the same form, associativity, and relative precedence.  
---
### Answer by username_8 on 2023-06-23. Score: 4
Con: Can lead to unreadable code
The syntax of ?: is pretty unintuitive. Python's X if Y else Z is slightly better. However, this problem becomes worse if many such if-else expressions are nested. For example, (a) ? (b ? c : d) : (e ? f : g) or even the following where it is easy to see what the code does but may be difficult to reason about how it does it:
String result = a ? "A" :
                b ? "B" :
                c ? "C" :
                d ? "D" :
                e ? "E" :
                f ? "F" :
                g ? "G" :
                h ? "H" :
                "I";

Though these examples are contrived, they show how ternary operators can lead to unwieldy code pretty quickly. Ternary operators are good for short conditional expressions; for larger conditions, if-else statements are better.
> **Comments:**
> **username_1** (2023-06-23): The right alternative to a ternary expression would have been an `if-then-else` *expression*. Statement cannot replace expression as statements in most languages cannot be used in the same place as expressions.  
> **username_5** (2023-06-27): @SK-logic an `if-then-else` expression is just a ternary operator with different syntax.  
> **username_1** (2023-06-27): @CoffeeTableEspresso it's exactly the `C?T:F` syntax that people have problems with. A more verbose syntax removes pretty much all the criticism of ternary expressions.  
---
### Answer by username_9 on 2023-06-30. Score: 2
If statement duplicates the part specifying what to do with the conditionally selected value:
if (condition) {
   use_value_now(alpha, beta, 0);
} else { 
   use_value_now(alpha, beta, 1);
}

It may be OK when the selected value is just assigned to the variable, but for the function call as in this example it almost looks like a dedicated variable should be defined for it. Then it is not so clear how (and if) this variable should be initialized when declared. Curly brackets (or they analogs in other languages) are also now mostly a requirement for the good coding style.
Compare this with
use_value_now(alpha, beta, condition ? 0 : 1);
> **Comments:**
> **username_10** (2023-06-30): This isn't necessarily true, e.g. `let gamma; if (condition) { gamma = 0 } else { gamma = 1 }; use_value_now(alpha, beta, gamma);`.  
> **username_9** (2023-06-30): It is how you write. But does not look very short.  
---
### Answer by username_11 on 2023-06-28. Score: 2
## Recommendation:

For expressions, provide the "same" set of conditional constructs that you provide for statements, and for readability, use similar syntax constructs.

The ternary operator's semantics match the if-then-else statement, but its syntax is very different - the operator uses special characters, the if-then-else statement uses readable keywords.

Typically, your language might also provide a switch-case statement, so you should also include a switch-case expression syntax.

Or you might even go one step further: make everything an expression, meaning that even "statements" return something. Then the if-then-else "statement" immediately replaces the ternary operator, without the need to learn two different syntaxes.

## Rationale:

Expressions that evaluate differently based on some condition are a very intuitive concept. See e.g. [Absolute Value](https://en.wikipedia.org/wiki/Absolute_value#Real_numbers), it uses an expression with two cases, and we all immediately understand what that means.

The main problem I see with the ternary operator is its syntax. It comes from the C language and follows the typical C cryptic style (is there any special character that we didn't use yet?).
---
### Answer by username_12 on 2023-06-23. Score: 1
# Pro:It’s more consice

This pretty much speaks for itself. Makes life considerably easier and more optimized.
---
### Answer by username_13 on 2023-06-28. Score: 1
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.
---
