Ternary Operator

Peter Lin
6 min readSep 9, 2019

--

A Concise If-Else Statement

How to Pronounce “Ternary”?

When I was first exposed to the term “Ternary Operator”, it gave me a headache trying to even say the word, let alone understanding it. So, how do you pronounce this word? “TernAry” like CanAry? “Terinary” like itinerary? Many others just try to say it and give up: “ I’ll just call it ‘tertiary operator’ ”. I personally pronounce it as “tern-er-ie”. It feels smoother so I just stuck with it. You can say it however you want. Whoever named it “ternary operator” is at fault.

What is a Ternary Operator?

A Ternary Operator is an operator that takes in three arguments or operands: a condition (or comparison), result upon true comparison, result upon false comparison. It is often used as a shortened version of If-Else statements.

How to Use a Ternary Operator?

A Ternary Operator can be structured in one line. It can be broken up into three parts. The first is an argument that serves as the condition and executes the next two arguments depending on the condition. The condition is followed by a “ ? ”, which is very helpful because it allows us to read the ternary operator as “questioning” whether the conditional statement is “true” or “false”. If the condition is true, it executes the code directly followed by the “ ? ” mark. If false, it executes the code following it. The code if true and if false is separated with a “ : ” sign.

(Condition) ? (If True) : (If False)

Ternary Operator VS If-Else Statement

Ternary Operators and If-Else Statements do not differ much aside from readability and conciseness. Short If-Else Statements can be converted to Ternary Operators.

if (Condition) {
// If True
} else {
// If False
}

Example:

let person = {
name: 'Richard',
age: 21
};

Here, we have a person named Richard and 21 years of age. We will using this information to compare Ternary Operators and If-Else Statements.

// If-Else Statementif (person.age >= 18) {
console.log("Adult")
} else {
console.log("Not Adult")
}
// Ternary Operator(person.age >= 18) ? console.log("Adult") : console.log("Not Adult")

For simple If-Else Statements like the above example, it is more efficient and convenient to use a ternary operator. As you conduct more and more complex If-Else Statements such as Nested If-Else Statements, Ternary Operators become less readable and harder to understand.

Example:

// If-Else Statementif (x === 1) {
if (y === 2) {
console.log("In Nested")
} else {
console.log("In Nested")
}
} else {
console.log("Not In Nested")
}
// Equivalent Ternary Operator(x === 1) ? (y ==== 2 ? "In Nested" : "In Nested") : "Not In Nested"

Although the Ternary Operator is written in one line, it can be hard to read the nested Ternary Operator inside the outer Ternary Operator. Since If-Else Statements can be organized with tabs, it is easier for us to read. However if your Ternary Operator is properly formatted, it can be easier to read.

Example:

// If-Else-If Statementif (x === 1) {
console.log("x equals 1")
} else if (x === 2) {
console.log("x equals 2")
} else if (x === 3) {
console.log("x equals 3")
} else {
console.log("x does equal 1, 2, or 3")
}
// Ternary Operator (Poorly Formatted)(x === 1)
? console.log("x equals 1")
: (x === 2)
? console.log("x equals 2")
: (x === 3)
? console.log("x equals 3")
: console.log("x does not equal 1, 2, or 3")
// Ternary Operator (Properly Formatted)(x === 1) ? console.log("x equals 1") :
(x === 2) ? console.log("x equals 2") :
(x === 3) ? console.log("x equals 3") :
console.log("x does not equal 1, 2, or 3")

In the poorly formatted Ternary Operator, it is difficult to read it. But if you properly format your Ternary Operator, its readability is as readable as the If-Else Statement. So, ultimately using ternary operators is beneficial to us as developers, especially in certain situations we come across when writing code.

Why Use Ternary Operator?

There are many situations where a Ternary Operator is useful. They are good for short tags in templating languages. For example, in a form you can mark the checkbox as “checked” if it fulfills a certain condition.

<form>
<input type="checkbox" (condition) ? "checked" : "" >
</form>

Another situation where a Ternary Operator is useful is switches in JavaScript. A personal example that I came across when Ternary Operators are useful in React:

<div 
className="ui card"
onClick={ bot.enlisted ? () => removeBot() : () => enlistBot() }
>
</div>

“onClick” is a synthetic event that is triggered by clicking on the “div” element. This synthetic event responds differently, depending on the condition “bot.enlisted”. If “bot.enlisted” is true, it responds with a callback function “removeBot” which would remove a bot from the bot army. But if “bot.enlisted” is false, it would instead execute “enlistBot”.

Wall-E GIF

Another similar example of using switches:

Ternary Operator Switch in React Stocks Lab

Here, we have another “onClick” synthetic event which executes differently depending if its “props.stock.bought” is “true” or “false”. It would execute the callback function “sellStock” if the stock is “bought”, or else it would execute the “butStock” callback function to buy the stock since the stock is not bought.

Stonks Meme

Ternary Operators are very good one line conditional statements that allow us to switch between actions depending on the condition. A more generic switch example:

let switch = true;
<div onClick={ switch ? !switch : !switch } >
</div>

“switch” is a variable that starts out “true”. However, when we click on the “div” element, it executes “!switch”, which changes “switch” to “false”. Thus, every time we click on the “div” element, the boolean property of “switch” changes between “true” and “false”.

Nintendo Switch GIF

Another example I came across in React that proves the usefulness of Ternary Operators:

Render with If-Else Statement

In React, we would need to return large blocks of JSX code to render using the If-Else Statement, with the condition “(this.state.loggedIn === false)”. This is because If-Else Statements cannot be used within JSX code. But a Ternary Operator can. We can simplify our code and reduce repetitive elements and components using a Ternary Operator.

Render with Ternary Operator

Finally, a popular use for Ternary Operators is assigning variables.

let variable = (Condition) ? (If True) : (If False)

This is useful when you want to assign a variable to different values depending on a certain condition. Using a previous example:

let person = {
name: 'Richard',
age: 21
};
let adult = (person.age >= 18) ? true : false// adult = true

Setting a variable depending on a condition can be efficiently executed with a Ternary Operator.

Conclusion

I think Ternary Operators are a very useful tool and I am starting to like it. It can be confusing at first, but I hope this blog can clear up some of the complications. As long as you properly format your Ternary Operators, it should be just as readable as If-Else Statements, if not even more. I recommend practicing Ternary Operators as it helps cut down stress on your fingers when writing lines of code as well as assist you in niche situations.

Avocado GIF

*This Avocado is how I feel about Ternary Operators now*

--

--

Peter Lin

Full stack web developer graduate from Flatiron School’s software engineering program. Built web applications with Ruby on Rails, JavaScript, React, and Redux.