Working with Ternary (Conditional) Operators in JavaScript

Updated: February 19, 2023 By: Khue Post a comment

This article is about ternary operators (or conditional operators) in Javascript.

The Basics

Ternary operators are a shorthand way of writing if-else statements. The syntax for a ternary operator is:

condition ? expression1 : expression2

If condition is true, the operator returns expressions; otherwise, it returns expression2.

Nested Ternary Operators

You can also use nested ternary operators to create more complex conditions.

Syntax:

condition1 ? expression1
  : condition2 ? expression2
  : condition3 ? expression3
  : condition4 ? expression4
  : expression5

There is no limit on conditions and expressions here, be it 2, 3, or N.

Example:

let score = 65;
let message = score >= 90 ? "Excellent"
             : score >= 80 ? "Good"
             : score >= 70 ? "Not Bad"
             : score >= 50 ? "Mediocre"
             : "Try Again"
console.log(message);

Output:

Mediocre

In the example above, the condition is evaluated from left to right. If score is greater than or equal to 90, the first expression Excellent is returned. Otherwise, the next nested ternary operator is evaluated. If score is greater than or equal to 80, the second expression Good is returned. Otherwise, the next nested ternary operator is evaluated, and so on.

More Examples

The following examples illustrate real-life use cases of using ternary operators when developing web applications.

Using ternary operator to set a default value

The code:

let name = null;
let displayName = name ? name : "Guest";
console.log(displayName);

Output:

Guest

In this example, if name is falsy, such as null, undefined, or an empty string, the operator returns the default value Guest.

Using ternary operator to check for a condition and execute a function

The code:

let isLoggedIn = true;

isLoggedIn ? displayDashboard() : displayLogin();
function displayDashboard() {
  console.log("Welcome to Sling Academy dashboard...");
}
function displayLogin() {
  console.log("Please log in.");
}

Output:

Welcome to Sling Academy dashboard...

In this example, the ternary operator checks whether the user is logged in or not. If the user is logged in, the displayDashboard() function will be called. Otherwise, the displayLogin() function will be triggered.

Using nested ternary operators to concatenate a string

The code:

let user = { name: "Sling Academy", age: 37, isPremium: true };

let message = "Welcome, " + user.name + ". You are " + user.age + " years old and you are a" + (user.isPremium ? " premium" : " regular") + " user.";

console.log(message);

Output:

Welcome, Sling Academy. You are 37 years old and you are a premium user.