Learn the concept
Operators
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a concise one-line alternative to if-else that returns a value. Unlike if-else, it's an expression that can be used in assignments, return statements, and JSX.
The ternary (conditional) operator is the only JavaScript operator that takes three operands.
Syntax: condition ? expressionIfTrue : expressionIfFalse
Key differences from if-else:
When to use ternary:
When to use if-else:
// if-else statement
let message;
if (age >= 18) {
message = 'Adult';
} else {
message = 'Minor';
}
// Ternary expression — same result, one line
const message = age >= 18 ? 'Adult' : 'Minor';
// In template literals
console.log(`Status: ${isActive ? 'Active' : 'Inactive'}`);
// In function returns
function getDiscount(isMember) {
return isMember ? 0.2 : 0;
}
// In React JSX
const Badge = ({ status }) => (
<span className={status === 'online' ? 'green' : 'gray'}>
{status === 'online' ? 'Online' : 'Offline'}
</span>
);Applying CSS classes based on component state, e.g., isActive ? 'btn-active' : 'btn-inactive'
Rendering different components or elements based on props or state directly inside JSX
Providing inline default values like const label = value ? value : 'N/A' for display purposes
Build a component that toggles between different UI states using ternary expressions
Practice converting if-else chains to ternaries and vice versa, evaluating readability trade-offs