Better Programming

Advice for programmers.

Follow publication

The JavaScript Ternary Operator

Andrew Koenig-Bautista
Better Programming
Published in
3 min readFeb 24, 2020

Photo by Jon Tyson on Unsplash

JavaScript Operators

JavaScript has several different types of operators. These include comparison, arithmetic, logical, and many more.

These operators can be further defined as either unary or binary. Let’s break down the difference between these two terms now as we move toward understanding ternary.

Unary

A unary operator takes just one operand, either before or after the operator:

operator operand || operand operatorfor example:x++ || ++x

Binary

A binary operator requires two operands, the most common examples being basic addition, subtraction, multiplication, and division:

operand operator operandx + y; || x - y; || x * y; || x / y;

Relational, bitwise, equality, and logical operators are also binary:

operand operator operanda few examples (non-exhaustive):x < y; // the less-than relational operator
x << y; // the left shift bitwise operator
x || y; // binary logical operator
x == y; // the equals operator

And that brings us to ternary.

The Ternary Operator

“The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy, followed by a colon (:), and finally, the expression to execute if the condition is falsy. — MDN

The syntax is shown below:

condition ? value1 : value2

If condition evaluates to true, the ternary operator will have the value of value1. If condition evaluates to false (or falsy), it has the value of value2.

let bouncerReply = (age >= 21) ? 'Access allowed' : 'Access denied';

You can also chain conditional operators:

let message = (tempCelsius > 95) ? 'Too hot!' :
(tempCelsius < 95) ? 'Too cold!' :
(tempCelsius === 95) ? 'Just right!' :
'This isn't porridge!';
  1. The first question mark checks condition tempCelsius > 95.
  2. If true, return 'Too hot!'. If not, check condition tempCelsius < 95.
  3. If true, return 'Too cold!'. If not, check tempCelsius === 95.
  4. If that’s true — it returns 'Just right!'. Otherwise, it continues to the expression after the final colon :, returning 'This isn't porridge!'.

Should You Use It?

The fact that I felt the need to include an explanation for the above sequence of ternary expressions gives away my answer to this question. Here is what the above code would look like using if..else:

Personally, I would recommend defaulting to if..else statements as opposed to using the ternary/conditional operator. Just my own opinion.

Chaining or nesting ternaries makes the minification they are touted for negligible. Sure, the if..else example is a few lines of code longer, but it is also infinitely more readable. Leave the minifying to the minifiers.

What’s the Difference?

The ternary operator is not simply a replacement for if..else constructs.

The difference is the ternary operator is an expression whereas an if..else construct is a statement. An expression returns a value, a statement does not.

At the end of the day, use of the ternary operator is a form of syntactic sugar, and as I wrote elsewhere, less code does not always equal more concise code.

Summary

Full disclosure, I do use ternary operators in my own code. Almost every instance as single-line variable assignments or simple conditionals. Once a situation would require nested or chained ternaries, I shift to if..else and that is what I recommend for you as well, dear reader.

I believe readability should always be prioritized when writing code. Bugs often stem from the misunderstanding of previously written code. Your future self will thank you, and so will any devs who work with your code.

Especially when the difference in code length or performance is negligible.

Thanks for reading!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Andrew Koenig-Bautista
Andrew Koenig-Bautista

Written by Andrew Koenig-Bautista

Web Developer, writer, bookworm, viewer of indie films. Passionate about problem-solving and building a more equitable -and joyful- world. Actively job seeking.

Write a response

Andrew — I’ll be honest, I’m not a fan of the click-bait subtitle.
Short answer — don’t chain ternary operators. It’s ugly, hard to read, and prone to errors. But for a single test (let a = b ? c : d) is good.
Marcin — yes switch case is good, except that it can only be used for equality tests in its cases, sadly.

--

The better solution for many if-else is switch-case. The ternary operator is good when you want to get a property from a variable that might be an object or null/undefined.

--