Javascript's Ternary Operator: A Compact Alternative to if/else
Javascript offers a ternary operator which acts like a one-line if
/else
statement with a single condition. It works really well for conditionally assigning a value to a variable.
For Assigning a Value to a Variable
Here’s what assigning a value to a variable conditionally using a ternary looks like. For the purposes of this example, imagine itemCost
is the cost of the current item and hasDiscount
has been set to true
or false
depending on whether this user gets a discount.
const markup = 0.3;
const baseItemPrice = itemCost * (1 + markup);
const itemPrice = hasDiscount ? baseItemPrice * 0.8 : baseItemPrice;
The part before the question mark is the condition. The next part is the code to be executed if the condition evaluates to true. After the colon, we have the code to run if the condition is false.
It would look like this if you wrote it as an if
statement:
const markup = 0.3;
const baseItemPrice = itemCost * (1 + markup);
if (hasDiscount) {
const itemPrice = baseItemPrice * 0.8;
} else {
const itemPrice = baseItemPrice;
}
Here’s what the ternary example above does in plain English. We create two variables: markup
which is how much we mark up our items and baseItemPrice
which is the price we charge after applying our markup. We assign a value to itemPrice
using a ternary. The ternary checks to see if the customer has a discount. If they do, it sets the final itemPrice
to 80% of the base price. If not, itemPrice
is set to baseItemPrice
.
For Other Operations
Imagine a user just submitted a form. You know the user is either from the US or the UK. You also know the user typed the word “color” as part of one of the fields. You’re going to use that to determine which country they are from and run a function to add them to an email list based on their location.
For the purposes of this example, we’ll assume the form responses have already been serialized to an object called responses
.
responses.colorField.includes('colour')
? addToUKList(responses.email)
: addToUSList(responses.email);
When to Use the Ternary
The ternary is a cool trick, but you shouldn’t use it all the time. It’s extremely important that your code is readable, and the ternary just doesn’t read as nicely as the humble if
statement.
I use them mostly for assignment, particularly when I have a series of conditional assignments in close proximity, just to make the code a little more compact. When I need to conditionally do something besides assignment, I’ll almost always reach for a different method.
Want More Like This?
If you liked this post, share your email below and I’ll send you more like it as they go live! Sharpen your Javascript skills and learn new techniques to level up your web development.
If you think the ternary will be useful, why not add the array reduce method to your toolkit as well!