Sling Academy
Home/JavaScript/Working with Ternary (Conditional) Operators in JavaScript

Working with Ternary (Conditional) Operators in JavaScript

Last updated: February 19, 2023

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.

Next Article: JavaScrip Throw Statements: Tutorial & Examples

Previous Article: Using Labeled Loops in JavaScript (3 Examples)

Series: Mastering Control Flow in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration