How to Use the Ternary Operator in JavaScript

The ternary operator is a concise way of expressing conditional statements in a single line of JavaScript code. Our expert explains how it works.

Written by Rory Spanton
Published on Jul. 13, 2023
Image: Shutterstock / Built In
Image: Shutterstock / Built In
Brand Studio Logo

Conditional statements allow programmers to control the execution of code based on logical conditions. Like many other programming languages, JavaScript features if/else statements that achieve this goal.

What Is The Ternary (Conditional) Operator in JavaScript?

An alternative to the if/else statement, the ternary operator allows JavaScript developers to write concise conditional statements. It is written as “?:” and takes three operands; a logical condition, a value to return if true, and a value to return if false

But it’s common knowledge among developers that if/else statements with lots of conditions can get messy. They often make scripts unnecessarily long, difficult to debug, and hard to maintain. Fortunately, JavaScript’s ternary operator provides an alternative to the if/else statement, allowing for more concise and maintainable code.

In this article, we’ll write conditional statements with the ternary operator and learn to use it in different situations.

More From Rory SpantonPolynomial Regression: An Introduction

 

Writing a Simple Expression With the Ternary Operator 

The ternary operator gets its name by being the only operator in JavaScript that takes three operands, or parts. The first part of a ternary operation is a logical condition that returns a true or false value. Then, after a question mark, come two expressions, separated by a colon. The first is an expression to execute if the logical condition is true, while the second expression executes if the condition is false. The generic form of the function is below.

condition ? exprIfTrue : exprIfFalse

The ternary expression is an alternative to the conventional if/else statement. The if/else statement below is equivalent to the ternary operation above.

if (condition) {
	exprIfTrue
} else {
	exprIfFalse
}

Because of its similarities to the if/else statement, using a simple ternary operation is straightforward. Let’s say we have a website where users can make an account. Once users sign in, we want to give them a custom greeting. We can create a basic function to do this using the ternary operator.

function generateGreeting(signedIn) {
  return signedIn ? "Hello, Rory" : "Hello, Customer"
}

generateGreeting(true)
// Returns "Hello, Rory"

generateGreeting(false)
// Returns "Hello, Customer"

This function takes a condition called signedIn, which is a true or false value that relates to whether a user has logged into their account. If the condition is true, the ternary operator returns a personalized greeting. If the condition is false, it returns a generic greeting.

This is a neat way of writing simple logic. If we used an if/else statement instead of a ternary operation, the function would take up more space to achieve exactly the same result.

 

Evaluate Truthy/Falsy Conditions With Ternary Operator

Just like if/else statements in JavaScript, ternary expressions can evaluate truthy or falsy conditions. These conditions might return true or false values, but might also return other values that JavaScript coerces to be true or false. For example, if a condition returns null, NaN, 0, an empty string (“”) or undefined, JavaScript will treat it as false in a ternary operation.

This behavior comes in handy when dealing with conditions that return missing values. We can use our custom greeting function from the previous example to show this. Giving this function a condition that returns null executes the “false” expression by default.

generateGreeting(null)
// Returns "Hello, Customer"

Although truthy and falsy conditions can be useful, they can also have unintended consequences. For example, we could assign a value of 1 or 0 to our condition signedIn. But a mistake in this assignment could result in signedIn having a NaN or undefined value. JavaScript would then treat the condition as false without any warning, which could lead to unexpected behavior.

To avoid situations like this, we can set conditions that test for exact values. If we only wanted to output a personalized greeting if signedIn has a value of 1, we could write the following.

function generateGreeting(signedIn) {
 return signedIn === 1 ? "Hello, Rory" : "Hello, Customer"
}

generateGreeting(1)
// Returns "Hello, Rory"

 

Using the Ternary Operator With Many Conditions

The ternary operator can also be an alternative to more complex if/else statements with several conditions. For example, we could check that members on our website are both signed in and have a paid membership before giving them a custom greeting. We can do this in a ternary operation by adding the extra condition using the && operator.

function generateGreeting(signedIn, paidMember) {
  return (signedIn && paidMember) ? "Hello, Rory" : "Hello, Customer"
}

generateGreeting(true, true)
// Returns "Hello, Rory"

generateGreeting(true, false)
// Returns "Hello, Customer"

Again, this phrasing is more concise than an if/else statement. But we can go even further with the ternary operator by specifying multiple “else” conditions.

For instance, we could use the ternary operator to determine which stage of life a customer is in based on their age. If we wanted to classify users as children, teenagers, adults, or seniors, we could use the following function ternary operation:

function classifyAge(age) {
  return age < 0 ? "Invalid Age" :
     	age < 13 ? "Child" :
     	age < 18 ? "Teenager" :
     	age < 65 ? "Adult" :
     	"Senior";
}

classifyAge(30)
// Returns “Adult”

Chaining together ternary operators like this saves plenty of space. Rewriting this function as a chain of if/else statements takes up around twice as many lines.

function classifyAge(age) {
  if (age < 0) {
	return "Invalid Age";
  } else if (age < 13) {
	return "Child";
  } else if (age < 18) {
	return "Teenager";
  } else if (age < 65) {
	return "Adult";
  } else {
	return "Senior";
  }
}

This is also an example where using if/else statements leads to less readable code. Although the ternary operator displays each condition and its corresponding return value in the same line, the if/else statement separates these pairings. This makes the logic of the if/else code harder to follow at a glance. If used within longer scripts, this might also make such code harder to debug, giving further reason to use the ternary operator.

 

Strengths and Limitations of the Ternary Operator

As seen above, the ternary operator in JavaScript has many strengths as an alternative to if/else statements.

Strengths of the Ternary Operator in JavaScript

  • It can represent conditional statements more concisely than if/else statements
  • In cases where conditions and return values are simple, ternary operator statements are easier to read than if/else statements
  • As a longstanding feature of JavaScript, it has excellent cross-browser compatibility

Yet there are situations where programmers should avoid using the ternary operator.

Limitations of the Ternary Operator in JavaScript

  • Conditional statements with longer expressions can be hard to read with the ternary operator’s inline syntax. These expressions could otherwise be split across many lines in an if/else statement, resulting in better readability.
  • Nested conditions are also better expressed as if/else statements than with the ternary operator. Although you can nest conditional statements with the ternary operator, the result is often messy and hard to debug. If/else statements lend themselves better to nested conditions because they are split over many lines. This visual separation makes each condition easier to understand and maintain.

More in JavaScript8 Common JavaScript Data Structures

 

Start Using the Ternary Operator in JavaScript

In summary, the ternary operator is a great way of phrasing conditional statements. Although it isn’t suited to dense expressions or nested conditions, it can still replace long if/else statements with shorter, more readable code. Though not to be overused, it is still essential knowledge for any accomplished JavaScript programmer.

Explore Job Matches.