Guide to the Ternary Operator in JavaScript

Introduction

A ternary operator is a three-operand operator that is supported in most programming languages, including JavaScript, Java, C++, C#, and many others. It is also referred to as a conditional operator because it is considered to be a more concise alternative to the conditional (if-else) statement.

In this guide, we will learn what the ternary operator is and how it works in JavaScript. Also, we'll do a brief comparison with the if-else statement, so we know when to use which one.

Ternary Operator in JavaScript

As in any other language, ternary operator in JavaScript has three operands:

(condition) ? returnExpressionIfTrue : returnExpressionIfFalse;

We can easily translate this to the corresponding if-else statement:

if (condition) {
    returnExpressionIfTrue;
} else {
    returnExpressionIfFalse;
}

This basically means that the condition and the returnExpressionIfTrue correspond to the if clause of the corresponding if-else statement, and the returnExpressionIfFalse corresponds to the else section of the mentioned statement.

If the condition evaluates as true, the returnExpressionIfTrue expression is executed. On the other hand, if the condition is evaluated as false, the returnExpressionIfFalse is executed.

Note: To be more precise, JavaScript checks if the condition evaluates as truthy or as falsy value. Falsy values are all values that JavaScript evaluates as false in a boolean expression - false, none, undefined, NaN, 0, -0, 0n, and "". All the other values are evaluated as true in a boolean expression - thus considered truthy.

How to Use Ternary Operator

A perfect way to explain the ternary operator would be to compare it with the if-else statement. Suppose we have a certain age and we want to check whether a user is younger than that or not:

let age = 21;
let result;

if(age >= 20){
    result = "User can view content";
} else {
    result = "User cannot view content";
}
console.log(result);

Let's rewrite this if-else block using ternary operator :

let age = 21;
let result = age >= 20 ? "User can view content" : "User cannot view content";

console.log(result);

Basically, anything before the question mark (?) is the condition we are checking. The other two operands are expressions, the first one before the semi-colon (:) and the second after. If the condition is true, the value of the result will be "User can view the content". Otherwise, the value assigned to the result will be "User cannot view the content".

Let's take a look at another interesting example:

let name = "John Doe";

if (name) {
    console.log("Hello " + name);
} else {
    console.log("Hello " + "Guest");
}

Since the name is a non-empty string, it is considered to be a truthy value. Therefore, this example will result in logging "Hello John Doe" in the console. If the name were an empty string - the output will be "Hello Guest". This scenario is easily convertible to the ternary operator:

let name = "John Doe";

name ? console.log("Hello " + name) : console.log("Hello " + "Guest");

Although maybe above the scope of this guide, another interesting solution is to use the logical or operator instead of the ternary operator. This will yield us with the absolutely the same result as the other two approaches:

console.log("Hello " + (name || "Guest"));

Handling Multi-Line Expressions With the Ternary Operator

Taking a look at the first expression, we will notice that we were able to collapse a five-line if-else block into a single-line ternary statement. Suppose we want to handle multi-line expressions with the ternary operator:

const age = 22;
let youth;

if (age <= 30) {
    youth = true;
    console.log("I am a Youth!");
} else {
    youth = false;
    console.log("I am an Adult!");
}

console.log(youth);

We would have to place these expressions in brackets and then separate each by a comma:

age <= 30
    ? ((youth = true), console.log("I am a Youth!"))
    : ((youth = false), console.log("I am an Adult!"));

Even though the code using ternary operators is shorter, even this two-line expression makes the ternary operator pretty hard to read and understand. That's the reason why it’s best not to use the ternary operator for multi-line expressions - a better alternative is to stick with the if-else block in situations like this.

Nested Ternary Operators

A nested ternary operator refers to the ability to place a ternary operator within another. These statements are used when we want to evaluate multiple conditions. For example, with the if-else statement we can use the else if statement to nest multiple conditions together:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

let studentScore = 65;
let studentGrade;

if (studentScore >= 70) {
    studentGrade = "A";
} else if (studentScore >= 60) {
    studentGrade = "B";
} else if (studentScore >= 50) {
    studentGrade = "C";
} else if (studentScore >= 45) {
    studentGrade = "D";
} else {
    studentGrade = "E";
}

console.log(`Your grade is ${studentGrade}`);

When we implement this with the ternary operator, we will have something like this:

let studentScore = 65;

let studentGrade = studentScore >= 70 ? "A" 
    : studentScore >= 60 ? "B" 
    : studentScore >= 50 ? "C" 
    : studentScore >= 45 ? "D" 
    : "E";

console.log(`Your grade is ${studentGrade}`);

This can quickly become difficult to read if we don't pay attention and properly understand how the ternary operator works. More importantly - even if you can read this - what about your colleagues? In cases like this, it is recommended we use the if-else or the switch statements rather than writing code that can confuse others.

Conclusion

As we've seen in this guide, ternary operator and if-else statement can be used pretty much interchangeably and it's up to you to decide when to choose one over the other. Generally speaking, the ternary operator is not designed to ultimately replace the if-else statement. Instead, it aims to be a valid alternative in scenarios where if-else just creates unnecessary overhead - when the outcome is so simple that anything besides a simple ternary operator takes too much space in the code.

In this guide, we took a look at what a ternary operator is and how to make use of it in JavaScript. It may seem a bit intimidating in the beginning, but after reading this guide you should understand how it works and what is the difference between a ternary operator and if-else, so you know when to choose one over the other.

Last Updated: May 30th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms