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

If you want to learn more about the Ternary Operator
consult the Introduction to Programming Course read more ⯈

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 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 is “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 of 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, nesting of ternary operators is used to assign a grade based on a score.

However, maintaining code readability is important when doing so.

Practical Examples

Comparing two numbers and determining the larger 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 the evaluation and assignment in a single line, simplifying our code and making it easier to read.

Assignment of values

The ternary operator is useful when a value needs to be assigned 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 category variable 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/ma'am" : "Hello";
}

This getGreeting function returns “Good morning, sir/ma’am” 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 it’s the best way to solve the problem they address.