What’s a Ternary Operator?

Matt Basile
Matt’s Lambda Minutes
5 min readJan 30, 2019

In programming, we use conditional logic for almost every problem we try to solve. Meaning that if something happens then do this, if not either proceed as is or do something else.

This concept drives a lot of the logic in our applications but can sometimes a headache to track and manage. What if there was a way to write it neater, cleaner, and faster?

That’s where ternary operations come into play. A ternary operator is simply a shortcut way to write a if/else statement. It generally condenses 5 lines of code down to 1–2 lines.

This post will review our traditional if/else statement, how we translate that to a ternary operator and then conclude with some real-life example.

If/Else Statements

The core idea of the if/else statement is simple: If this condition is met, then execute this piece of code. Otherwise, continue as normal, or execute this other piece of code. This cycle can continue for a while but ultimately we are returned a solution.

In basic JavaScript we use if, else if and else statements to achieve this goal. Here’s an example of a function that determines if a user is above the drinking age:

function canYouHaveACocktail (age){
if(age >= 21){
alert("Congrats! You're old enough to drink, have a cold one!")
} else if(age === 20){
alert("So close! But sorry, no drinks for you!")
} else{
alert("Sorry young gun. How bout a cola?")
}

As you can see the example above utilizes our three conditional statements in order to render a tailored response to our users.

While it’s totally functional code, doesn’t it look a bit busy? Sometimes it’s hard to track everything going on there. Let’s take a peek at the syntax for a ternary operator and we can dissect which looks better.

Ternary Syntax

Ternary syntax is awesome because it takes the lengthy if/else statement and shrinks it mightly. Take a look at the yntax for a ternary operator here:

Might seem complicated because of the brackets so here’s a list breakdown of what we have.

  1. Blue — Write the test case, in our example that would be age >= 21
  2. Purple — ?, just write a question mark, this is like initiating our conditional statement,
  3. Green — Truthy Response, write the desired result we want to see if true. From our example, that would be, alert("Congrats! You're old enough to drink. Have yourself a cold one!")
  4. Purple — :, use the semicolon to break between your truthy and falsey responses.
  5. Red — Falsey Response, write the desired result we want to see if false, From our example, that would be, alert("Sorry young gun. How bout a cola?")
  6. If we combine them all together it looks like this:

Pretty neat stuff huh? But you might be wondering, what happens to our unique age===20 edge case? We can solve this by placing a ternary operator inside another ternary operator…

Yea it’s mindblowing at first, but when you break it down we’ve got his in the bag. Let’s first look at what our example above would look like as a ternary inside a ternary.

age >= 21 ? alert("Congrats! You're old enough to drink. Have yourself a cold one!") : age === 20 ? alert("So close! But sorry no drinks for you!") : alert("Sorry young gun. How bout a cola?")

Viola! We have a ternary nested inside another ternary, allowing us to test for unique edge cases and are regular if/else statement. However, if you’re finding this difficult to read you’ll be happy to learn that we can use linebreaks to our advantage.

Instead, we can format our nested ternaries to look like this:

In code, that would look like:

age>= 21 ? alert("Congrats! You're old enough to drink. Have yourself a cold one!")
: age === 20 ? alert("So close! But sorry no drinks for you!")
: alert("Sorry young gun. How bout a cola?")

Anytime you run into a colon feel free to break it down to another line. If you like the idea of breaking down ur ternary like that, Twisted Oak provides a nice explanation of how the equals our standard if/else here.

Ternary in Action

Now that we’ve got the syntax down let’s see a basic example of how we can use our ternaries to manipulate our UI.

My first example will be in vanilla JS and the second will be in React. I’ve found that using ternaries has become much more important and useful in React as it allows us to dynamically update our UI based on our state.

Vanilla JS Example: https://codepen.io/mattbasile/pen/wNzmGM?editors=1111

ReactJS: https://codesandbox.io/s/oll35yp4yy

In both instances, we are using our ternary operators to update the classes of our headers to style. Followed by manipulating the text that is being rendered.

In the vanilla JS we do this by targeting our h1 and using its classList and innerText methods to manipulate the h1 rendering on the DOM. We can use our ternary to check to see if a specific class exists or a certain string is being represented and then manipulate our h1 accordingly.

In the React example, we’re relying on our state to dictate our UI representation. We use a button that evokes a function which sets the state of our colorful property via setState. Then in our UI rendering, we can use ternaries to monitor whether or not colorful is true or false which will, in turn, dictate our text and our classes.

In both instances, the logic is very similar but in React we no longer target the DOM and simply rely on our state to dictate our UI decisions.

Wrap Up

I hope you enjoyed this brief dive into the world of ternary operators. They’re a nice simple way to clarify our code and in some instances make it more dynamic.

If you find yourself lost or confused by any of the content please reach out and I’d be happy to review with you!

As always Happy Coding!!

--

--

Matt Basile
Matt’s Lambda Minutes

Full Stack Developer sharing updates of his journey through Lambda School’s course. Check-in for a recap of core concepts and how-to guides.