Mastering the Ternary Operator in JavaScript
🤔 What is the Ternary Operator?
The ternary operator in JavaScript is a concise way to write an if...else statement. It allows you to perform conditional logic in a single line — perfect for quick, simple decisions. ⚡
>>“When brevity meets clarity — that's the power of the ternary operator.” ✨
📌 Syntax
Ternary Operator Syntax
condition ? expressionIfTrue : expressionIfFalse;✅ If the condition is true, the expression before the colon (:) executes.
❌ If the condition is false, the expression after the colon executes.
🌐 Basic Example
Basic Ternary Example
const age = 20;
const message = age >= 18 ? "✅ You can vote" : "❌ You cannot vote";
console.log(message);📦 Assigning with Ternary
You can assign values conditionally using the ternary operator — great for inline logic:
Assigning a Value
const isDarkMode = true;
const theme = isDarkMode ? "dark-theme" : "light-theme";🧠 Nesting Ternary Operators
Ternary expressions can be nested, but be cautious — they can quickly become unreadable. Use parentheses for clarity.
Nested Ternary Example
const score = 85;
const grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";
console.log(grade);Note
🛑 Avoid deep nesting! If logic becomes complex, prefer if...else blocks for better readability.
💡 Ternary vs if...else
| Feature | Ternary Operator | if...else |
|---|---|---|
| Length | Short, inline | More verbose |
| Use Case | Simple decisions | Complex conditions |
| Readability | Great for quick logic | Better for branching logic |
📚 Further Reading
>>“Write code that speaks — sometimes a ternary whisper is louder than an if shout.” 💬