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 lineslet 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 : falseValuelet canVote = age >= 18 ? true : false;
// Using in variable assignmentlet fee = isMember ? 10 : 25;
// Using in return statementsfunctiongetDiscount(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 returnedlet 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 valueslet username = inputName ? inputName : "Guest";
// 2. Conditional rendering (React/Vue style)let buttonText = isLoading ? "Loading..." : "Submit";
// 3. CSS class nameslet className = isActive ? "btn-active" : "btn-inactive";
// 4. Form validation messageslet errorMsg = email.includes("@") ? "" : "Invalid email address";
// 5. API response handlinglet displayData = data ? data : "No data available";
// 6. Conditional function callslet 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 ternarylet 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 partlet x = condition ? "true"; // ERROR: missing : falseValue// ✅ FIX: Always provide both valueslet x = condition ? "true" : "false";
// ❌ MISTAKE 2: Using ternary for multiple statements
condition ? (doSomething(), doAnother()) : (doElse());
// ✅ FIX: Use if-else for multiple statementsif (condition) {
doSomething();
doAnother();
} else {
doElse();
}
// ❌ MISTAKE 3: Confusing = with ===let result = x = 5 ? "yes" : "no";
// ✅ FIX: Use comparison operatorlet result = x === 5 ? "yes" : "no";
// ❌ MISTAKE 4: Overly complex nested ternarylet category = a > b ? (c > d ? (e > f ? "A" : "B") : "C") : "D";
// ✅ FIX: Use if-else for readabilitylet 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.