Breaking Down the Ternary Operator

Michael Causey
3 min readDec 28, 2020

So this was one area I struggled with when I first ran across it, but has recently become somewhat of a default in my coding (under the right conditions, which will be noted later). Hopefully this article will help another up-and-coming coder figure this operator out early in their career.

Ternary Operator vs. If/Else Statement

Like a lot of beginning coders, I originally learned the if/else statements when coding. Once I was introduced to Ternary Operators, after an initial adjustment period, I found the use to be cleaner and clearer, especially when pairing with another programmer and our code needing to be easy to read.

Before we get into the detailed look of when to use which, lets look at how ternary operators are constructed

Ternary Operator

As you can see above, we have three pieces to each ternary. The first is the condition, which is checked first to determine what happens. If the condition is true, the first expression (noted as isTrue) will run. If the condition is false, the second (noted as isFalse) will run.

Below is the same function (a function to determine if a given number is above the value 5), written as both an if/else statement and a ternary.

As you can see, the ternary comes through much cleaner, with less lines of code. Now this is pretty basic, so below is a segment of code that was written for my Flatiron School final project, using a ternary to display information.

Clearly, this one is a bit more complicated, as I had established expressions based on a true/false relationship based far past a specific return. Also, in the condition, I made sure to note that not only it did exist, but it had a length of over 0, making sure it was declared and defined. In my first expression, in the event my instructions existed, it would map over the instructions (they were brought in as an array) and listed in an ordered list for display. If my instructions were not passed in or did not exist, a simple text return was generated.

A couple personal notes for Ternary Operators to finish with. First, I tend not to use these operators if my expression has more than one operation to run, as it can cause the code to become unmanageable fairly quickly. Lastly, this is a case where only two outcomes can be decided, either true or false. In the event that multiple expressions can be possible, it should be that if/else if statements continue to be used, as anything more than a true/false condition render the Ternary unusable.

--

--

Michael Causey

Flatiron School DC. Learning to code one day at a time.