javascript-condicional-ternario

What is and how to use the ternary operator in Javascript

  • 4 min

The ternary operator ? (also known as the conditional operator) is a tool that allows us to write conditional statements in a more concise and elegant way.

This operator is a shorthand for the if...else structure and is useful when we want to make decisions based on a condition.

If you want to learn more, check out the Introduction to Programming Course

It consists of three parts: a conditional expression, an expression that is evaluated if the condition is true, and another expression that is evaluated if the condition is false.

The basic syntax of the ternary operator is as follows:

condition ? true_expression : false_expression
Copied!
  • condition: An expression that evaluates to true or false.
  • true_expression: The expression that will be executed if condition is true.
  • false_expression: The expression that will be executed if condition is false.

Basic Example

Suppose we want to write a message that says “You are an adult” if age is greater than or equal to 18, and “You are a minor” if age is less than 18.

We could write the code as follows:

const age = 18;
let message;

if (age >= 18) {
    message = "You are of legal age";
} else {
    message = "You are a minor";
}

console.log(message); // Result: You are of legal age
Copied!

However, using a ternary conditional, we can simplify this code into a more compact form.

const age = 18;
const message = age >= 18 ? 'You are of legal age' : 'You are a minor';

console.log(message); // Result: You are of legal age
Copied!

Nesting Ternary Operators

It is possible to nest ternary operators for more complex conditional expressions. For example,

const grade = 80;

const finalResult = grade >= 90 ? 'A' :
                     grade >= 80 ? 'B' :
                     grade >= 70 ? 'C' : 
                                      'D';

console.log(finalResult); // Result: B
Copied!

In this example, a nesting of ternary operators is used to assign a grade based on a score.

However, it is important to maintain code readability when doing so.

Practical Examples

These examples are intended to show how to use the ternary operator. It does not mean it is the best way to solve the problem they address.