The ternary operator is a concise way to write conditional expressions in JavaScript. It is often used as a shorthand for if...else statements when you want to assign values or return results based on a condition.

💡 Syntax Overview
condition ? expressionIfTrue : expressionIfFalse
Here’s how it works:
conditionis evaluated first.- If
conditionis true,expressionIfTrueruns and its value is returned. - If
conditionis false,expressionIfFalseruns and its value is returned.
| if...else | ternary operator |
|---|---|
let result;
if (age >= 18) {
result = 'Adult';
} else {
result = 'Minor';
}
|
let result = age >= 18 ? 'Adult' : 'Minor'; |
💡 When to Use
Use the ternary operator for simple, concise conditionals that return values. Avoid using it for complex or multi-line logic to keep code readable.
📌 Deep Dive: Basic Example
const score = 75;
const grade = score >= 60 ? 'Pass' : 'Fail';
console.log(grade);
The ternary operator can also be nested, but be cautious as this can reduce readability:
📌 Deep Dive: Nested Ternary
const num = 0;
const sign = num > 0 ? 'Positive' : num < 0 ? 'Negative' : 'Zero';
console.log(sign);
⚠️ Avoid Overusing Nested Ternaries
Nested ternary operators can be hard to read and debug. Prefer if...else for complex conditions.
The ternary operator can also be used directly in expressions or JSX (in frameworks like React) to conditionally render values or elements.
💡 Summary
- The ternary operator is a compact alternative to
if...elsefor conditional expressions. - Syntax:
condition ? exprIfTrue : exprIfFalse. - Best for simple conditionals returning values.
- Use cautiously with nested ternaries to maintain readability.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What is the correct syntax for the ternary operator?
Question 2 of 2
What is a common pitfall when using nested ternary operators?
Loading results...