Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 10
Ternary Operator & Conditional Expressions
The ternary operator is a one-line shorthand for if/else. It's heavily used in React for conditional rendering and for assigning values based on conditions.
Ternary Syntax
- condition ? valueIfTrue : valueIfFalse - Returns one of two values
- Use for simple conditions - Assigning variables, inline expressions, short returns
- Avoid nesting - Nested ternaries are unreadable: condition ? a : condition2 ? b : c
- Real-world - React JSX: {isLoggedIn ? <Dashboard /> : <Login />}
- Nullish coalescing ?? - Alternative: value ?? defaultValue (for null/undefined only)
Ternary Code
const age = 20;
// Ternary: one-line if/else
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
// Assigning based on condition
const score = 85;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
console.log(grade); // "B" (nested - avoid for complex logic)
// Real-world: greeting
const hour = new Date().getHours();
const greeting = hour < 12 ? "Good morning โ๏ธ" : hour < 18 ? "Good afternoon ๐ค๏ธ" : "Good evening ๐";
console.log(greeting);
// Real-world: display text
const items = 5;
const label = items === 1 ? "item" : "items";
console.log(`${items} ${label} in cart`); // "5 items in cart"Tip
Tip
Use ternary for simple value assignments and React conditional rendering: const message = isLoggedIn ? 'Welcome back!' : 'Please log in'. Avoid nesting ternaries - if you need more than one condition, use if/else for clarity.
Ternary Operator & Conditional Expressions in JavaScript
Common Mistake
Warning
Nesting ternary operators makes code unreadable: a ? b : c ? d : e ? f : g. If you catch yourself nesting ternaries, refactor to if/else or switch. Readability always beats cleverness.
Practice Task
Note
Use ternary operators for these: (1) Assign 'even' or 'odd' based on a number. (2) Create a pluralized label: '1 item' vs '5 items'. (3) Set a greeting based on the hour: morning/afternoon/evening (but note this nesting is borderline - consider if/else).
Quick Quiz
Key Takeaways
- The ternary operator is a one-line shorthand for if/else.
- condition ? valueIfTrue : valueIfFalse - Returns one of two values
- Use for simple conditions - Assigning variables, inline expressions, short returns
- Avoid nesting - Nested ternaries are unreadable: condition ? a : condition2 ? b : c
Finished this lesson?