JavaScript Ternary Operator

The ternary operator is the only JavaScript operator that takes three operands. It provides a concise way to write simple if/else statements in a single line. The syntax is: condition ? expressionIfTrue : expressionIfFalse.

Basic Syntax

The ternary operator evaluates a condition. If the condition is true, it returns the first expression. If false, it returns the second expression.

Basic Ternary
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"

let hour = 14;
let greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(greeting); // "Good afternoon"

let isRaining = true;
console.log(isRaining ? "Bring umbrella" : "Enjoy the sun");
// "Bring umbrella"

Ternary vs if/else

The ternary operator is best for simple assignments and return values. Use if/else for complex logic, side effects, or multiple statements.

Comparing Ternary and if/else
let score = 85;

// Using if/else (4 lines)
let result1;
if (score >= 60) {
  result1 = "Pass";
} else {
  result1 = "Fail";
}
console.log(result1); // "Pass"

// Using ternary (1 line)
let result2 = score >= 60 ? "Pass" : "Fail";
console.log(result2); // "Pass"

// Ternary in template literals
let items = 5;
console.log(`You have ${items} item${items === 1 ? "" : "s"}`);
// "You have 5 items"

Nested Ternary

You can nest ternary operators to handle multiple conditions. However, deeply nested ternaries can be hard to read — use sparingly and consider if/else for complex cases.

Nested Ternary
let score = 75;

// Nested ternary (use with caution)
let grade = score >= 90 ? "A"
           : score >= 80 ? "B"
           : score >= 70 ? "C"
           : score >= 60 ? "D"
           : "F";

console.log(grade); // "C"

// Another example
let num = 0;
let sign = num > 0 ? "positive"
          : num < 0 ? "negative"
          : "zero";
console.log(sign); // "zero"

Using Ternary in Assignments

Ternary operators are particularly useful when assigning values based on conditions, setting function arguments, or building strings dynamically.

Practical Ternary Uses
// Dynamic assignment
let isLoggedIn = true;
let message = `Welcome ${isLoggedIn ? "back" : "guest"}!`;
console.log(message); // "Welcome back!"

// Function argument
let darkMode = true;
let bgColor = darkMode ? "#333" : "#fff";
console.log(bgColor); // "#333"

// Conditional method call
let arr = [3, 1, 4, 1, 5];
let sorted = true;
let output = sorted ? arr.sort((a, b) => a - b) : arr;
console.log(output); // [1, 1, 3, 4, 5]

// Ternary for null checks
let user = { name: "Alice" };
let displayName = user ? user.name : "Anonymous";
console.log(displayName); // "Alice"

When NOT to Use Ternary

Avoid ternary when you need multiple statements, side effects, or complex branching logic. If you struggle to read a ternary at a glance, use if/else instead.

When to Prefer if/else
let action = "save";

// BAD: ternary with side effects
// action === "save" ? saveData() : deleteData(); // avoid this

// GOOD: use if/else for side effects
if (action === "save") {
  console.log("Saving data...");
  // Additional save logic here
} else {
  console.log("Deleting data...");
  // Additional delete logic here
}

// GOOD: ternary for simple values
let label = action === "save" ? "Save" : "Delete";
console.log(label); // "Save"
📝 Note: Nested ternary operators should be formatted with each condition on its own line for readability. If the ternary has more than 2 levels of nesting, refactor to if/else or a lookup object.
Exercise:
What does the expression true ? "yes" : "no" return?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.