Language: EN

javascript-condicional-ternario

What is and how to use the ternary operator in Javascript

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 version of the if...else structure and is useful when we want to make decisions based on a condition.

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
  • condition: An expression that evaluates as 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 of legal age” 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

However, using a ternary conditional, we can simplify this code in 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

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

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

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

Practical Examples

Compare Two Numbers and Determine the Greater One

Suppose we have two variables, “a” and “b”, representing two integers, and we want to determine which of the two is greater. We could write the code as follows:

let a = 5;
let b = 8;
let greater;

if (a > b) {
    greater = a;
} else {
    greater = b;
}

With the ternary conditional, we can reduce this code to a single line:

let a = 5;
let b = 8;
let greater = (a > b) ? a : b;

Again, the ternary conditional allows us to perform evaluation and assignment in a single line, simplifying our code and making it easier to read.

Value Assignment

The ternary operator is useful when you need to assign a value based on a simple condition in a single line of code.

let age = 20;
let category = (age >= 18) ? "adult" : "minor";

console.log(`The person is ${category}`);

This example assigns the string “adult” to the variable category if age is greater than or equal to 18; otherwise, it assigns the string “minor”.

Return Value in Functions

The ternary operator can also be used to determine the return value of a function based on a condition.

function getGreeting(isFormal) {
    return isFormal ? "Good morning, sir/madam" : "Hello";
}

This getGreeting function returns “Good morning, sir/madam” if the isFormal parameter is true; otherwise, it returns “Hello”.

Handling Default Values

The ternary operator can also be useful for assigning default values based on a condition.

let name = user ? user.name : "Guest";

In this example, if the user variable is defined, its name property is assigned to the name variable. If user is not defined, the string “Guest” is assigned as the default value.

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