What is a Ternary Operator?

What is a Ternary Operator?

ยท

3 min read

Almost nothing prepares a newbie developer for the shock of seeing code that is used by enterprise solutions ๐Ÿคฃ. Most tutorials that work with mock databases (that are hardcoded within the application) do not prepare one for the reality of working with actual databases, making calls to these databases and expecting responses.

An image of a little girl sitting on a man's laps while she's being taught by the man

A Relatable Explanation

Today I'm not going to dwell on the experience of production/live code, I'm going to demystify another concept that has newbie developers scratching their heads or having the "what have I gotten myself into?" positions ๐Ÿ˜…. We're going to be looking at ternary operator and it's going to be a fairly short walkthrough.

We'll be building on what you know about conditional (if else) statement. Ternary operator is used to minimize the amount of code written when using an if-else statement. When writing code, it's typically advised that one writes as few lines of code as possible. This is sound advice, but can be used to create codebases that are very confusing for junior developers to maintain.

Two ants trying to lift a stone together

Implementing A Ternary Operator

To better emphasize the difference between the traditional if-else statement and ternary operators, I'll show you the difference below.

if (5 > 10) {
      var outcome = "5 is greater than 10";
} else  {
      var outcome = "5 is not greater than 10";
}

Console.log(outcome);

The code above is quite basic, it simply instructs the machine to return a response that tells you whether or not 5 is greater than 10. However, if you noticed, we used seven lines of code to write this instruction. There are a lot of conditional statements in enterprise codebases as such what may look like just seven lines of code can spiral into over 700 lines if used repeatedly.

Now let's show you the exact same thing as the above if-else but using a ternary operator. The code snippet below should show you how.

var outcome = 5 > 10 ? "5 is greater than 10" : "5 is not greater than 10";

Console.log(outcome);

The code snippet above is the same as the if-else statement, but it's a lot shorter. Basically, ternary statements are divided into three; the condition being evaluated, the response if the condition is true, and the response if the condition is false. 5>10 is the condition being evaluated, 5 is greater than 10 is the response if 5>10 is true, while 5 is not greater than 10 is the response if 5>10 is false.

An image of a girl walking down a dark path, holding on to three balloons that look like planets

Finally...

It helps to use a ternary operator to quickly evaluate and return responses to methods or functions or quick comparisons. The lines of code you save can in the future save you or your team hours of reading what should be redundant code.