DocsHub
Control Flow

Ternary Operator

Learn how to write concise conditional expressions using the ternary operator in JavaScript.

Ternary Operator

The ternary operator is a compact, one-line way to write a simple if/else statement.

Instead of writing four lines for a basic condition, you write one. It is the shortest way to make a decision in JavaScript.

// Regular if/else — 4 lines
if (age >= 18) {
  status = "Adult";
} else {
  status = "Minor";
}

// Ternary — 1 line, same result
let status = age >= 18 ? "Adult" : "Minor";

Same logic, same output — just shorter.


Syntax

condition ? valueIfTrue : valueIfFalse

It has three parts — which is why it's called ternary (ternary means "composed of three parts"):

  • condition — the expression being evaluated
  • ? — separates condition from the true value, read it as "then"
  • valueIfTrue — returned when condition is truthy
  • : — separates the two values, read it as "otherwise"
  • valueIfFalse — returned when condition is falsy

Read it like a sentence:

age >= 18 ? "Adult" : "Minor"
// "Is age 18 or above? Then Adult, otherwise Minor."

Basic Example

let age = 20;
let label = age >= 18 ? "Adult" : "Minor";

console.log(label); // Adult
let isRaining = true;
let advice = isRaining ? "Take an umbrella." : "Enjoy the sunshine.";

console.log(advice); // Take an umbrella.

Inside console.log Directly

You don't always need to store the result in a variable. You can use the ternary inline wherever a value is expected.

let score = 85;

console.log(score >= 50 ? "Pass" : "Fail"); // Pass
let cartCount = 0;

console.log(`You have ${cartCount} ${cartCount === 1 ? "item" : "items"} in your cart.`);
// You have 0 items in your cart.

That last example is a classic real-world use — handling singular and plural text based on a count.


Ternary With Functions

You can call functions as the result of a ternary too.

let isLoggedIn = true;

isLoggedIn ? showDashboard() : showLoginPage();

This works — but if the function calls are long or complex, a regular if/else is more readable.


Chaining Ternaries — Use With Caution

You can nest ternaries to handle more than two cases.

let score = 72;

let grade = score >= 90 ? "A"
          : score >= 80 ? "B"
          : score >= 70 ? "C"
          : score >= 60 ? "D"
          : "F";

console.log(grade); // C

This works and some developers write it this way. But honestly — if you have more than two cases, a regular if/else if chain or a switch is much easier to read and maintain. Don't chain ternaries just to be clever.

Nested ternaries get hard to read fast. If you find yourself chaining more than one, switch to if/else. Code is read far more often than it is written.


When to Use Ternary vs if/else

The ternary is not a replacement for if/else — it is a tool for specific situations.

SituationUse
Assigning one of two values to a variable✅ Ternary
Rendering one of two things inline✅ Ternary
Simple true/false decision in one line✅ Ternary
Running multiple lines of code❌ Use if/else
More than two outcomes❌ Use if/else or switch
Complex logic with && and `
// ✅ Perfect for ternary — simple value assignment
const greeting = isLoggedIn ? "Welcome back!" : "Please sign in.";

// ❌ Wrong use of ternary — multiple lines of logic
isLoggedIn
  ? (fetchUserData(), updateUI(), logActivity())  // messy
  : showLoginForm();

// ✅ This should be if/else
if (isLoggedIn) {
  fetchUserData();
  updateUI();
  logActivity();
} else {
  showLoginForm();
}

A Real Example — Theme Switcher

let isDarkMode = true;

let theme = isDarkMode ? "dark" : "light";
let icon = isDarkMode ? "🌙" : "☀️";
let buttonLabel = isDarkMode ? "Switch to Light Mode" : "Switch to Dark Mode";

console.log(`Theme: ${theme}`);         // Theme: dark
console.log(`Icon: ${icon}`);           // Icon: 🌙
console.log(`Button: ${buttonLabel}`);  // Button: Switch to Light Mode

Three decisions, three lines — all clean and readable with ternary.


Summary

  • The ternary operator is a one-line if/else for simple decisions
  • Syntax: condition ? valueIfTrue : valueIfFalse
  • Best used for assigning values or inline expressions
  • Avoid nesting ternaries — switch to if/else when logic grows
  • It does not replace if/else — it complements it for simple cases

On this page