JavaScript Roadmap — Day 20: Ternary Operator — The Conditional Shortcut

 

JavaScript · Day 20 of 180 · Beginner Phase

Ternary Operator — The Conditional Shortcut

Write cleaner conditional logic in one line. The ternary operator turns 5 lines of if-else into a single, readable expression that returns a value. Master this and your code becomes more elegant.

Day 20 / 180
Beginner Phase
🕐 10 min read
💻 7 code examples
🎯 3 practice tasks

Here is the code that confuses many beginners:

Why write 5 lines when you can write 1?
// ❌ Long way — 5 lines
let message.
if (age >= 18) {
  message = "Adult";
} else {
  message = "Minor";
}

// ✅ Short way — 1 line (Ternary Operator)
let message = age >= 18 ? "Adult" : "Minor";

// Which would you rather write and read?

The ternary operator is one of my favourite JavaScript features. It takes a simple if-else statement and turns it into a single line that actually returns a value. Today I'll show you exactly how it works, when to use it, and when to avoid it. By the end of this lesson, you'll be writing cleaner conditional logic without thinking twice.

1. The Problem — Verbose If-Else

Sometimes you just want to assign a value based on a condition. But if-else takes 5 lines for something simple:

Verbose If-Else
// Simple conditional assignment — but so many lines!
let message.
if (age >= 18) {
  message = "Adult";
} else {
  message = "Minor";
}

// Same thing in one line with ternary:
let message = age >= 18 ? "Adult" : "Minor";

// Which would you rather read and write?

💡 The key insight: The ternary operator is not a statement — it's an expression. That means it returns a value. This is the fundamental difference from if-else, which executes code but doesn't return anything.

2. Ternary Syntax — The Building Block

The ternary operator has three parts: condition ? valueIfTrue : valueIfFalse

Ternary Syntax Examples
// Basic syntax — condition ? trueValue : falseValue
let canVote = age >= 18 ? true : false;

// Using in variable assignment
let fee = isMember ? 10 : 25;

// Using in return statements
function getDiscount(price, isPremium) {
  return isPremium ? price * 0.8 : price;
}

// Using directly in console.log
console.log(score > 50 ? "Passed! 🎉" : "Failed 😢");

// Ternary returns a value — can be stored, used, or returned
let result = (x > y) ? "x wins" : "y wins";

3. Common Use Cases — Where Ternary Shines

Ternary is perfect for these scenarios:

Real-World Use Cases
// 1. Setting default values
let username = inputName ? inputName : "Guest";

// 2. Conditional rendering (React/Vue style)
let buttonText = isLoading ? "Loading..." : "Submit";

// 3. CSS class names
let className = isActive ? "btn-active" : "btn-inactive";

// 4. Form validation messages
let errorMsg = email.includes("@") ? "" : "Invalid email address";

// 5. API response handling
let displayData = data ? data : "No data available";

// 6. Conditional function calls
let result = isValid ? processData(input) : handleError(input);

4. Chaining Ternary — Multiple Conditions

You can chain ternaries for multiple conditions, but use sparingly. Too many chained ternaries become unreadable.

Chained Ternary (Use Carefully)
// Grade calculator with chained ternary
let grade = score >= 90 ? "A"
         : score >= 80 ? "B"
         : score >= 70 ? "C"
         : score >= 60 ? "D"
         : "F";

// Same thing with if-else (more readable)
let grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else grade = "F";

// ⚠️ Nested ternary — VERY hard to read (avoid!)
let result = a > b ? (c > d ? "a > b and c > d" : "a > b but c <= d") : "a <= b";
⚠️ Warning: Nested Ternaries
If you find yourself nesting ternaries or chaining more than 2 conditions — just use if-else or switch. Your future self (and teammates) will thank you. Readability > Brevity.

5. Best Practices — When to Use Ternary

Ternary is a tool. Use it wisely:

✅ DO — Simple value assignments
let status = isLoggedIn ? "Welcome back" : "Please log in";
✅ DO — Return values from functions
return isValid ? data : null;
✅ DO — Conditional rendering
<div>{isLoading ? "Loading..." : content}</div>
❌ DON'T — Complex logic with side effects
// Don't do: condition ? (x = 5, y = 10) : (x = 0, y = 0);
❌ DON'T — More than 2 chained conditions
If you need else-if chains, use if-else or switch.

6. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE 1: Forgetting the else part
let x = condition ? "true";  // ERROR: missing : falseValue

// ✅ FIX: Always provide both values
let x = condition ? "true" : "false";

// ❌ MISTAKE 2: Using ternary for multiple statements
condition ? (doSomething(), doAnother()) : (doElse());

// ✅ FIX: Use if-else for multiple statements
if (condition) {
  doSomething();
  doAnother();
} else {
  doElse();
}

// ❌ MISTAKE 3: Confusing = with ===
let result = x = 5 ? "yes" : "no";

// ✅ FIX: Use comparison operator
let result = x === 5 ? "yes" : "no";

// ❌ MISTAKE 4: Overly complex nested ternary
let category = a > b ? (c > d ? (e > f ? "A" : "B") : "C") : "D";

// ✅ FIX: Use if-else for readability
let category;
if (a <= b) category = "D";
else if (c <= d) category = "C";
else if (e <= f) category = "B";
else category = "A";

7. Try It Yourself — Ternary Playground

Click the buttons below to see the ternary operator in action. Change the values and watch how the output changes instantly!

✏️ Ternary Playground — Test Your Understanding
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Try changing the values above!

8. Practice Tasks

Task 1 — Easy: Even or Odd

Write a function isEven(number) that uses the ternary operator to return "Even" if the number is even, and "Odd" if it's odd. Test with numbers 5, 10, and 17.

Task 2 — Medium: Max of Two

Write a function getMax(a, b) that returns the larger number using the ternary operator. Then write a function getMaxOfThree(a, b, c) using nested ternary operators.

Task 3 — Hard: Grade Calculator with Ternary

Create a function getGrade(score) that returns the letter grade using ONLY ternary operators (no if-else). Use the following scale: A (90-100), B (80-89), C (70-79), D (60-69), F (below 60). Then refactor to use if-else and compare readability.

Next Lesson
Day 21 — For Loops
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts