I'm in a little bit of a bind. Very early on in my software development career, I learned about these things called ternary statements, and I thought they were the coolest thing ever. I started using them everywhere...but now, I'm just having different thoughts. Let's take a step back for a minute though.
What are ternary statements?
Ternary statements are (put simply) shortcut if statements that look like this:
const val = "test";
const showTest = val == "test" ? "The value was a test value" : "The value was not a test value";
(Go to this MDN article to learn more about ternary operators: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)
Spoken in plain english that code is translated to:
IF val is equal to the value of "test"
THEN set the variable showTest to the value of "The value was a test value"
ELSE set the variable showTest to the value of "The value was not a test value"
What's the alternative??
To me, early on in my career, this seemed like an absolute godsend. The alternative code looks like this:
const val = "test";
let showTest;
if (val == "test") {
showTest = "The value was a test value";
} else {
showTest = "The value was not a test value";
}
And if you hated more lines of code like I did early on, this seems like a no brainer. A two line solution verses a seven line solution is really no question.
So what's the problem?
Remember how in the beginning I referenced that I was in a bind...well here's the bind.
In the application that I have built (and now work on maintaining for the company that I work for) I used ternary statements EVERYWHERE. I used it for absolutely everything that I could. Less lines of code, right? Well I've realized that the only thing that cares about lines of code in your app is this website right here:
And besides that, going after less lines of code isn't always the best. In fact, I run into two problems now going back to the application and trying to refactor the ternary statements a little bit.
- The mental overhead it takes to make a change in the logic.
Ternary operators only support one action for each block of the if. So in the code above, maybe all I wanted to do in the beginning was set the showTest variable to a string...but what if now I also want to fire off a function if val does equal test? I have to go back, remember what it was doing, try and remember why I thought there would be no other actions necessary, and then refactor it to look like the second example I've posted up anyways.
- The distinct lack of code readability
Code like this that does so much in so few lines of code really loses it's luster when it comes to readability. It may scan better, but it also does provide a mental block when it comes to readability that the other example does not.
So what?
All in all, I will probably still use ternary operators...even after everything I said. Why? Because there is definitely a time and a place for them, just like with everything. What we have learned here where I work though, is that time and place isn't littered through the codebase, just trying to cut a 127 line file down to a 122 line file.
What are your thoughts on ternary operators?
Latest comments (39)
For most of my coding career I've been a solo coder, meaning I have all the freedom in the world to make the decisions I want on practices for my own websites, etc. In all that time, I have never thought, "Gosh, I wish I was using ternary operators right now!" I like the expanded logic, it was always much easier for me to look over my code in a quick glance.
That’s fair, it was never really a conscious decision for me either...I just read about it one day and thought it had this visual elegance...and it just sort of happened😂😂😂😂
Thank you for reading!!
hugs her ugly monster ternary statements don't listen to him you're beautiful. /joke
I agree with you that they have a time and place, but I also love to use them <3 tho' I don't do it for readability or fewer code lines... I do them 'cause they look prettier.
I'm a simple girl sorry lol X3
Thanks for the article!
😂😂😂😂😂😂😂😂😂
Thanks for the laugh and thanks for reading!!!
(I do agree with you though...they bring a visual elegance to code that really can't be matched!!)
I think we forgot the use for return statement:
Also, since c99, one can write:
Which I love and also put in Gwion 😄
I would like to add that not all ternaries are equal. Python's context is much easier to understand imho
Interesting!! Taking away the “?” And the “:” of the ternary operators and replacing them with words. I think I may like that!!
Thanks for reading!!
Order is altered thought:
In C you would write:
not
I think your frustration comes from cases where you neatly define a variable using a ternary operator and then you have to do something for one of the branches of the condition. It feels like duplicating code if you add a new if afterwards and it looks ugly if you turn the ternary into an if/else block and then add the action in one of the branches. I feel you.
However, I think that if we put readability first, then checking a condition twice is the least of our problems. I would much prefer:
than the alternative:
One block defines a value, the other is executing an action. I think we should be allowed to use the hammer of our choice for each individual nail.
Interesting discussion here! The main reason why I always preferred if/else was that I could easily set a breakpoint inside THEN or ELSE. Nowadays I think Google Chrome can set a breakpoint inside a ternary THEN or ELSE, too.
One thing I saw in this discussion here and used intuitively is that I’ve used a ternary to do a simple assignment to a variable, if there is some kind of logic/function calls I would rather use an if-else.
After all these years I still have to think if ? or : comes first when I am writing it xD. Readability depends heavily if the ternary is long or short.
I personally hate them, I personally find an if/else faster to determine the code flow than this behaviour.
The notification that this is a conditional occurs at the start of the line, whereas the ternary operator occurs roughly half way through the line, requiring you to read most of the line to understand the impact.
Minimising the number of lines of code is not effective in making code more readable. I'm a C programmer by trade, I could write the whole program on one line if I really wanted.
It's annoying and not beneficial.
How fast someone with zero familiarity of the code can pick up what is happening is the true measure of readability. Especially if that person is a non coder, good code will read like a document in the language it is written in.
Usually in this kind of things I have a pragmatic, almost obvious, approach: ternary operator is a tool that has its pros and cons, it has contexts where it is useful and contexts where you can use it, but it is quite a stretch...
It is true, however, that C-style ternary operator lacks somehow readability.
In Ada we have a kind of ternary operator too, but its syntax is (IMHO) much more readable
We have
casetoo (switchfor you C people)The
(...)around theifand thecaseare mandatory.I find it useful in simple contexts where a classical
if ... then ... elsewould look redundant. It is fundamental in defining inline functions (I think it was the reason for introducing it)and also in some pre/post condition. Suppose you have a function
Foothat returns 0.0 when its argument is negative and a value larger than the input otherwise. You can writeAlso the implication A => B is nicely expressed with the ternary
I definitely agree that there is a time and a place for everything! I’ll still use ternary operators, just not as frequently!!
Thanks for the in depth breakdown, and thanks for reading!!!
I agree for the most part ternaries become cumbersome fast. I'd like to address the next hurdle down the path and say that if you are writing single line of statements in Java then you should use braces as it is easier to tweak later without having to add them in. Also, I've personally come across some terribly formatted code where single line if blocks were used along with inconsistent indent and it becomes a nightmare to read.
Ternary operators were amazing when I first learned about them.
I agree that there is a time and place for them. For a simple concept (someone mentioned assigning values or triggering a this or that scenario) they are great. But, beyond a short line of code, they do get messy and hard to read, even if its less code.
Is it really better code if is take my slow, human brain more time to figure it out before I can make changes?
I totally think that no, if my brain has to think too much to make a change, I did something wrong!!
And that’s what I’ve been running into a lot lately, decisions I’ve made to have less lines, or to do something faster, I’m definitely regretting
Too much thinking is also why I avoid using while loops. 🤷🏽♀️
Yes!!!
I think I’ve only written like 5 while loops in my whole career!!
Thanks so much for reading!!
I've yet to use one outside of practice assignments that say to use a while loop.
if/else or for loops for the win. I'll use a simple ternary, as a treat.
Foreach is what I always try and reach for (no pun intended)😆😆