Quick Tip: How to Use the Ternary Operator in JavaScript

Share this article

Quick Tip: How to Use the Ternary Operator in JavaScript

In this tutorial, we’ll explore the syntax of the ternary operator in JavaScript and some of its common uses.

The ternary operator (also known as the conditional operator) can be used to perform inline condition checking instead of using if...else statements. It makes the code shorter and more readable. It can be used to assign a value to a variable based on a condition, or execute an expression based on a condition.

Syntax

The ternary operator accepts three operands; it’s the only operator in JavaScript to do that. You supply a condition to test, followed by a questions mark, followed by two expressions separated by a colon. If the condition is considered to be true (truthy), the first expression is executed; if it’s considered to be false, the final expression is executed.

It’s used in the following format:

condition ? expr1 : expr2

Here, condition is the condition to test. If its value is considered to be true, expr1 is executed. Otherwise, if its value is considered to be false, expr2 is executed.

expr1 and expr2 are any kind of expression. They can be variables, function calls, or even other conditions.

For example:

1 > 2 ? console.log("You are right") : console.log('You are wrong');

Using the Ternary Operator for Value Assignment

One of the most common use cases of ternary operators is to decide which value to assign to a variable. Often, a variable’s value might depend on the value of another variable or condition.

Although this can be done using the if...else statement, it can make the code longer and less readable. For example:

const numbers = [1,2,3];
let message;
if (numbers.length > 2) {
  message = 'The numbers array is too long';
} else {
  message = 'The numbers array is short';
}

console.log(message); // "The numbers array is too long"

In this code example, you first define the variable message. Then, you use the if...else statement to determine the value of the variable.

This can be simply done in one line using the ternary operator:

const numbers = [1,2,3];
let message = numbers.length > 2 ? 'The numbers array is too long' : 'The numbers array is short';

console.log(message); // "The numbers array is too long"

Using the Ternary Operator for Executing Expressions

Ternary operators can be used to execute any kind of expression.

For example, if you want to decide which function to run based on the value of a variable, you can do it like this using the if...else statement:

if (feedback === "yes") {
  sayThankYou();
} else {
  saySorry();
}

This can be done in one line using the ternary operator:

feedback === "yes" ? sayThankYou() : saySorry();

If feedback has the value yes, then the sayThankYou function will be called and executed. Otherwise, the saySorry function will be called and executed.

Using the Ternary Operator for Null Checks

In many cases, you might be handling variables that may or may not have a defined value — for example, when retrieving results from user input, or when retrieving data from a server.

Using the ternary operator, you can check that a variable is not null or undefined just by passing the variable name in the position of the condition operand.

This is especially useful when the variable is an object. If you try to access a property on an object that’s actually null or undefined, an error will occur. Checking that the object is actually set first can help you avoid errors.

For example:

let book = { name: 'Emma', author: 'Jane Austen' };
console.log(book ? book.name : 'No book'); // "Emma"

book = null;
console.log(book ? book.name : 'No book'); // "No book"

In the first part of this code block, book is an object with two properties — name and author. When the ternary operator is used on book, it checks that it’s not null or undefined. If it’s not — meaning it has a value — the name property is accessed and logged into the console. Otherwise, if it’s null, No book is logged into the console instead.

Since book is not null, the name of the book is logged in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator will fail, since book is null. So, “No book” will be logged in the console.

Nested Conditions

Although ternary operators are used inline, multiple conditions can be used as part of a ternary operator’s expressions. You can nest or chain more than one condition to perform condition checks similar to if...else if...else statements.

For example, a variable’s value may depend on more than one condition. It can be implemented using if...else if...else:

let score = '67';
let grade;
if (score < 50) {
  grade = 'F';
} else if (score < 70) {
  grade = 'D'
} else if (score < 80) {
  grade = 'C'
} else if (score < 90) {
  grade = 'B'
} else {
  grade = 'A'
}

console.log(grade); // "D"

In this code block, you test multiple conditions on the score variable to determine the letter grading of the variable.

These same conditions can be performed using ternary operators as follows:

let score = '67';
let grade = score < 50 ? 'F'
  : score < 70 ? 'D'
  : score < 80 ? 'C'
  : score < 90 ? 'B'
  : 'A';

console.log(grade); // "D"

The first condition is evaluated, which is score < 50. If it’s true, then the value of grade is F. If it’s false, then the second expression is evaluated which is score < 70.

This keeps going until either all conditions are false, which means the grade’s value will be A, or until one of the conditions is evaluated to be true and its truthy value is assigned to grade.

CodePen Example

In this live example, you can test how the ternary operator works with more multiple conditions.

If you enter a value less than 100, the message “Too Low” will be shown. If you enter a value greater than 100, the message “Too High” will be shown. If you enter 100, the message “Perfect” will be shown.

See the Pen
Ternary Operator in JS
by SitePoint (@SitePoint)
on CodePen.

Conclusion

As explained in the examples in this tutorial, the ternary operator in JavaScript has many use cases. In many situations, the ternary operator can increase the readability of our code by replacing lengthy if...else statements.

Related reading:

FAQs on How to Use the Ternary Operator in JavaScript

What is the Syntax of the Ternary Operator in JavaScript?

The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a result for true, and a result for false. The syntax is as follows:

condition ? value_if_true : value_if_false

In this syntax, the condition is an expression that evaluates to either true or false. If the condition is true, the operator returns the value_if_true. If the condition is false, it returns the value_if_false.

Can I Use Multiple Ternary Operators in a Single Statement?

Yes, you can use multiple ternary operators in a single statement. This is known as “nesting”. However, it’s important to note that using too many nested ternary operators can make your code harder to read and understand. Here’s an example of how you can nest ternary operators:

let age = 15;
let beverage = (age >= 21) ? "Beer" : (age < 18) ? "Juice" : "Cola";
console.log(beverage); // Output: "Juice"

Can Ternary Operators Return Functions in JavaScript?

Yes, the ternary operator can return functions in JavaScript. This can be useful when you want to execute different functions based on a condition. Here’s an example:

let greeting = (time < 10) ? function() { alert("Good morning"); } : function() { alert("Good day"); };
greeting();

How Does the Ternary Operator Compare to If-Else Statements in Terms of Performance?

In terms of performance, the difference between the ternary operator and if-else statements is negligible in most cases. Both are used for conditional rendering, but the ternary operator can make your code more concise.

Can Ternary Operators be Used Without Else in JavaScript?

No, the ternary operator in JavaScript requires both a true and a false branch. If you don’t need to specify an action for the false condition, consider using an if statement instead.

How Can I Use the Ternary Operator with Arrays in JavaScript?

You can use the ternary operator with arrays in JavaScript to perform different actions based on the condition. Here’s an example:

let arr = [1, 2, 3, 4, 5];
let result = arr.length > 0 ? arr[0] : 'Array is empty';
console.log(result); // Output: 1

Can Ternary Operators be Used for Multiple Conditions?

Yes, you can use ternary operators for multiple conditions. However, it can make your code harder to read if overused. Here’s an example:

let age = 20;
let type = (age < 13) ? "child" : (age < 20) ? "teenager" : "adult";
console.log(type); // Output: "teenager"

Can Ternary Operators be Used in Return Statements?

Yes, you can use ternary operators in return statements. This can make your code more concise. Here’s an example:

function isAdult(age) {
return (age >= 18) ? true : false;
}
console.log(isAdult(20)); // Output: true

Can Ternary Operators be Used with Strings in JavaScript?

Yes, you can use ternary operators with strings in JavaScript. Here’s an example:

let name = "John";
let greeting = (name == "John") ? "Hello, John!" : "Hello, Stranger!";
console.log(greeting); // Output: "Hello, John!"

Can Ternary Operators be Used with Objects in JavaScript?

Yes, you can use ternary operators with objects in JavaScript. Here’s an example:

let user = { name: "John", age: 20 };
let greeting = (user.age >= 18) ? "Hello, Adult!" : "Hello, Kid!";
console.log(greeting); // Output: "Hello, Adult!"

Dianne PenaDianne Pena
View Author

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

conditionalsoperators
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week