Home >Web Front-end >JS Tutorial >Quick Tip: How to Use the Ternary Operator in JavaScript

Quick Tip: How to Use the Ternary Operator in JavaScript

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-09 08:38:20495browse

Quick Tip: How to Use the Ternary Operator in JavaScript

This tutorial will explore in-depth the syntax and common usage of JavaScript ternary operators.

JavaScript ternary operator (also known as conditional operators) is used to perform inline condition checking, instead of if...else statements. It makes the code more concise and easy to read, and can assign values ​​to variables or execute expressions based on conditions.

Key points

  • JavaScript ternary operator allows inline conditional checking, making the code shorter and easier to read. It accepts three operands: a condition to be tested, and two expressions separated by colons. If the condition is true, the first expression is executed; if the condition is false, the second expression is executed.
  • The ternary operator can be used to assign values, execute expressions based on conditions, and check whether the variable is null or undefined. It can also handle multiple conditions in the operator's expression by nesting or linking conditions, similar to the if…else if…else statement.
  • While the ternary operator can improve code readability by replacing the lengthy if…else statement, excessive use of nested ternary operators can make the code difficult to read. It should also be noted that the ternary operator requires a true and false branches.

Grammar

The ternary operator accepts three operands; this is the only operator in JavaScript that does so. You provide a condition to test, followed by a question mark, followed by two expressions separated by colons. If the condition is considered to be a true value, the first expression is executed; if the condition is considered to be a false value, the final expression is executed.

The format of its use is as follows:

<code class="language-javascript">condition ? expr1 : expr2</code>

where condition are the conditions to be tested. If its value is true, then expr1 is executed. Otherwise, if its value is a false value, then expr2 is executed.

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

Example:

<code class="language-javascript">1 > 2 ? console.log("You are right") : console.log('You are wrong');</code>

Use ternary operator for value assignment

One of the most common use cases for ternary operators is to determine the value to assign a value to a variable. The value of a variable usually depends on the value of another variable or condition.

While this can be achieved using the if...else statement, this will make the code longer and harder to read. For example:

<code class="language-javascript">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"</code>

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

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

<code class="language-javascript">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"</code>

Execute expression using ternary operators

The ternary operator can be used to execute any type of expression.

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

<code class="language-javascript">if (feedback === "yes") {
  sayThankYou();
} else {
  saySorry();
}</code>

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

<code class="language-javascript">condition ? expr1 : expr2</code>

If the value of feedback is "yes", the sayThankYou function will be called and executed. Otherwise, the saySorry function will be called and executed.

Use ternary operator for null value check

In many cases, you may be working on variables that may or may not have defined values—for example, when entering a search result from a user, or when retrieving data from a server.

Using the ternary operator, you can check if the variable is not null or undefined by placing the variable name in the conditional operand.

This is especially useful when a variable is an object. An error occurs if you try to access properties of an object that is actually null or undefined. First checking whether the object is set can help you avoid errors.

Example:

<code class="language-javascript">1 > 2 ? console.log("You are right") : console.log('You are wrong');</code>

In the first part of this code block, book is an object with two properties (name and author). When using the ternary operator for book, it checks if it is not null or undefined. If not - which means it has a value - then access the name property and log it to the console. Otherwise, if it is null, record "No book" to the console instead.

Since book is not null, the title of the book will be recorded in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator will fail because book is null. Therefore, the "No book" will be recorded in the console.

Nesting Conditions

Although the ternary operator is used for inline, multiple conditions can be used as part of the ternary operator expression. You can nest or link multiple conditions to perform condition checks similar to if...else if...else statements.

For example, the value of a variable may depend on multiple conditions. You can use if...else if...else to achieve:

<code class="language-javascript">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"</code>

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

The same conditions can be performed using the ternary operator, as shown below:

<code class="language-javascript">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"</code>

First evaluate the first condition, i.e. score >= 90.

This will continue until all conditions are false, which means that the value of grade is 'F', or until one of the conditions is evaluated as true and its true value is assigned to grade.

Conclusion

As shown in the example in this tutorial, there are many use cases for JavaScript ternary operators. In many cases, ternary operators can improve code readability by replacing verbose if...else statements.

(Subsequent content, such as the FAQ part, is recommended to handle it separately as needed due to the length of the article.)

The above is the detailed content of Quick Tip: How to Use the Ternary Operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn