How to Use the Ternary Operator in JavaScript

The if statement is one of the most used conditional statements in all programming languages.

In JavaScript, there is an operator known as a conditional ternary operator that can replace the if statement. It's shorter and more readable.

Like a traditional if statement, the ternary operator in JavaScript assigns a certain value to a variable depending on a condition. It is the only operator in JavaScript that takes three operands.

This tutorial will teach you everything you need to know about the ternary operator in JavaScript. We'll cover it's syntax, implementation, and advanced functionality like nested ternary operators and multiple operations.

Table of Contents

You can skip to a specific section of this JavaScript ternary operator tutorial using the table of contents below:

Ternary Operator Syntax

In JavaScript, the traditional conditional statement using if and else looks like this:

if (condition)
outcome = ‘result1’;
else
outcome = ‘result2’;

Writing the same statement using ternary operator looks like this:

outcome = (condition) ? ‘result1’ : ‘result2’;

With the ternary operator, if the condition is true, the value of the first expression is returned. If it is false, the value of the second expression is returned.

Let's break this down further:

  • First, a variable is created to which the value will be assigned. In this case, the variable is outcome. Depending on the condition, this variable will be assigned different values.
  • On the right-hand side, you write the condition.
  • The condition is followed by a question mark (?). The question mark is to be read as ‘was that true?’
  • The possible outcomes follow the question mark, separated by a colon.

Let’s take a look at another example of the ternary operator in JavaScript.

Consider an object named person that is defined by name, age, and driver property.

let person = {
  name: ‘Michael’,
  age: 21,
  driver: null
};

We want to run a program to find if the age of the person is 16 or greater. If the age is greater than 16, the program should return Yes and if it is not, the program should return No. This can be done by using the traditional JavaScript if statement like this:

if (person.age >= 16) {
  person.driver = 'Yes';
} else {
  person.driver = 'No';
}

What if the same exact thing can be achieved in just one line of code?

That is where the ternary operator comes in. Here’s how you can do it:

person.driver = person.age >= 16 ? 'Yes' : 'No';

Now that you know how a ternary operator works, let’s explore more about how it can be used in JavaScript.

In the next example, we are going to consider a more complex example. Let's assume there is a football arena that offers tickets at two prices: $15 for the general public and $10 for students.

The program will first decide whether or not the patron is a student and will return the price of the ticket accordingly.

To start, let's create a variable named isStudent:

let isStudent = false;

Now that we know the patron is not a student, here’s how we'll write the corresponding ternary operator:

let.price = isStudent ? 10 : 15;
console.log (price);

Since the value of the Boolean variable isStudent is false in this case, the program will return the value of the price variable as 15.

Nested Ternary Operators in JavaScript

When there are more than two conditions, we need to use a nested ternary operator.

A nested ternary operator refers to a ternary operator within another ternary operator. .

Consider the previous example, where a football game provides discounted prices to students. This time let’s add another condition where the football arena gives discounts to senior women.

In this scenario, let us assume that the price for tickets is $15 for the general public, $10 for students, and $7 for senior women.

Here’s how we can codify this logic in JavaScript using nested ternary operators:

let isStudent = false;
let isSeniorWoman = true;
let price = isStudent ? 10 : isSeniorWoman ? 7 : 15
console.log(price);

The output here will be 7.

Let's break this down:

  1. The first step is to check if the patron is a student. In this case, isStudent is false. Therefore, only the code after the first colon (:) is executed.
  2. After the first colon, there is another conditional isSeniorWoman. This is true in this case. Therefore only the code after ? but before : is executed.
  3. The value finally returned by the variable price is, therefore, 7.

Multiple Operations within a JavaScript Ternary Operator

Ternary operators allow multiple operations to be run within them. These operations have to be separated by a comma.

Optionally, you can also use parenthesis to group your code. Here's an example of this:

let isStudent = true;
let price = 15;
isStudent ? (
  price = 10,
  alert('Please verify the student ID')
) : (
  alert('Enjoy the match.')
);

In this code block, the price of the match is set to $15. If the patron is a student, the price is automatically set to $10 and an alert is sent to the cashier asking them to verify the student ID. But if the variable isStudent returns false, the alert is sent as Enjoy the match.

If/else vs Ternary Operator: When to Use Which

The if/else statement is fine to use for statements that run on the basis of an outside condition.

However, it can be replaced comfortably by a ternary operator if there are just two outcomes. In the case of more than two outcomes, the ternary operator should be avoided because nested ternary operators quickly become complicated and tough to understand.

My recommendation is that anything that can fit into a single line of code can be done using a ternary operator while in other cases if/else statement should be preferred.

As an example, here's a short program that will be become very confusing if rewritten using a ternary operator.

const lightColor = 'red';
 
if (lightColor === 'green') {
  console.log('Go');
} else if (lightColor === 'yellow') {
  console.log('Slow down');
} else if (lightColor === 'red') {
  console.log('Stop');
} else {
  console.log('The traffic light is broken');
}

Final Thoughts

You should now have a good understanding of the ternary operator and how to use it.

You should also be able to easily pick between if/else and ternary when it comes to writing a certain code.

With that said, it's a personal choice whether or not to use the ternary operator since all the functions can be fulfilled by if/else statement.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on September 8th, 2020