Ternary Operator
Imagine you ask your friend: "Is it raining?"
Your friend replies in one short line: "Yes? Take an umbrella. No? Wear sunglasses." 🌧️😎
No long explanation, just a quick decision.
In the If-Else lesson, we learned how to make decisions like this:
That is 6 lines for a very small decision. JavaScript gives us a shortcut to write the same thing in just one line:
let item = isRaining ? "Umbrella ☂️" : "Sunglasses 😎";
This shortcut is called the ternary operator.
What Is the Ternary Operator?
The ternary operator is a short way to choose between two values based on a condition. It works like a one-line if-else.
Why is it called "ternary"? "Ternary" means three parts. This is the only operator in JavaScript that takes three operands:
- A condition
- A value if true
- A value if false
Syntax
condition ? valueIfTrue : valueIfFalse
| Part | Symbol | Meaning |
|---|---|---|
| Condition | before ? | The question to check |
? | Question mark | Asks: "Is this true?" |
| Value if true | between ? and : | Used when the condition is true |
: | Colon | Means "otherwise" |
| Value if false | after : | Used when the condition is false |
Read it like a question in English:
isRaining ? "Umbrella" : "Sunglasses"
↓ ↓ ↓
Is it raining? Then umbrella. Otherwise sunglasses.
Your First Ternary Operator
How It Works, Step by Step
- JavaScript checks the condition
age >= 18→20 >= 18→ true ✅ - Since it is true, it picks the value before the
:→"Adult" "Adult"is stored instatus
If age were 15:
15 >= 18→ false ❌- It picks the value after the
:→"Minor"
If-Else vs Ternary: Side by Side
Both give exactly the same result. The ternary is just shorter.
Real-Life Examples
Example 1: Even or odd
Example 2: Free delivery 🚚
Example 3: Movie ticket price 🎬
Example 4: Login message 👤
Example 5: Stock status 📦
Example 6: Singular or plural
This is a very common trick to write correct English in messages!
Using Ternary Inside Template Literals
The ternary operator fits perfectly inside ${ } in template literals.
Using Ternary with Functions
You can use the ternary operator to return a value from a function.
With an arrow function, it becomes even shorter:
Using Ternary with Truthy and Falsy Values
The condition doesn't have to be a comparison. Any truthy or falsy value works.
Tip: For setting default values, you can also use
||or??from the Operators lesson:let displayName = userName || "Guest";
Nested Ternary (Multiple Conditions)
You can put a ternary inside another ternary to check more than two possibilities.
How JavaScript reads it:
marks >= 90 ? → false → move to the next check
marks >= 75 ? → true → "B" ✅
Key points:
- Writing each condition on a new line makes it easier to read.
- But don't overuse nested ternaries. More than 2 levels quickly becomes confusing.
❌ Hard to read:
let result = a > b ? a > c ? "a" : "c" : b > c ? "b" : "c"; // 😵
✅ Better with if-else:
let result;
if (a > b && a > c) {
result = "a";
} else if (b > c) {
result = "b";
} else {
result = "c";
}
Rule: If a ternary is hard to read in one look, switch to if-else.
Ternary Is an Expression, If-Else Is a Statement
This is the key difference between them.
- A ternary is an expression. It produces a value, so you can use it anywhere a value is expected.
- An if-else is a statement. It performs actions, but does not produce a value.
// ✅ Ternary gives a value, so you can store it
let status = age >= 18 ? "Adult" : "Minor";
// ❌ if-else cannot be stored like this
let status = if (age >= 18) { "Adult" } else { "Minor" }; // SyntaxError
That is why the ternary is great for choosing values, while if-else is better for running blocks of code.
When to Use Ternary (and When Not To)
✅ Use ternary when:
- You are choosing between two values
- The logic is short and simple
- You want to store or return a value
- You are inside a template literal
let fee = isStudent ? 50 : 100;
❌ Avoid ternary when:
- There are many conditions (use if-else or switch)
- Each branch has multiple lines of code
- You are only running actions, not choosing a value
// ❌ Not a good use: only running actions
isLoggedIn ? showDashboard() : showLoginPage();
// ✅ Better and clearer
if (isLoggedIn) {
showDashboard();
} else {
showLoginPage();
}
Common Mistakes to Avoid
| Mistake | Example | Problem | Fix |
|---|---|---|---|
Missing the : part | age > 18 ? "Adult" | ❌ SyntaxError | Always include both parts: ? ... : ... |
Swapping ? and : | age > 18 : "Adult" ? "Minor" | ❌ SyntaxError | ? comes first, then : |
Using = in the condition | x = 5 ? "yes" : "no" | Assigns instead of comparing | Use === |
| Too many nested levels | a ? b ? c : d : e ? f : g | Very hard to read | Use if-else |
| Writing multi-line blocks | cond ? { ...many lines } : ... | Messy code | Use if-else |
Quick Summary Table
| Task | Example |
|---|---|
| Basic ternary | let x = cond ? "yes" : "no"; |
| Inside a template literal | `Hi ${isMorning ? "Morning" : "Evening"}` |
| Return from a function | return age >= 18 ? "Adult" : "Minor"; |
| Default value | let name = user ? user : "Guest"; |
| Multiple conditions | a > 90 ? "A" : a > 75 ? "B" : "C" |
Key Takeaways
- The ternary operator is a one-line if-else that chooses between two values.
- The syntax is
condition ? valueIfTrue : valueIfFalse. Read?as "if true" and:as "otherwise". - It is the only operator with three parts, which is why it is called "ternary."
- It is an expression, so you can store it, return it, and use it inside template literals.
- Use it for short, simple decisions. For many conditions or multi-line logic, use if-else instead.