Quantcast
Channel: What are pros/cons of ternary conditional operators? - Programming Language Design and Implementation Stack Exchange
Viewing all articles
Browse latest Browse all 10

Answer by Rydwolf Programs for What are pros/cons of ternary conditional operators?

$
0
0

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.


Viewing all articles
Browse latest Browse all 10