What are pros/cons of ternary conditional operators? - Programming Language Design and Implementation Stack Exchange
Ternary Operator
Is using the ternary operator bad practice?
Im trying to understand the "Conditional (ternary) operator." Do these 2 codes mean the same thing? I wrote the if statement
Videos
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.
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.
What do people think about using the ternary '?' operator instead of ifelse?
Do you use it, how often, what are best practices concerning this way of writing conditional statements?