Ternary Operator
Overview
The conditional (ternary) operator is the only JavaScript operator that takes three operands. It is frequently used as a clean, one-line shorthand for a simple if/else statement.
The syntax is: condition ? expressionIfTrue : expressionIfFalse.
Unlike if/else, which is a statement, the ternary operator is an expression. This means it evaluates to a value, so you can directly assign its result to a variable or return it from a function.
Syntax
const age = 20;
// Reads like English: Is age >= 18? If yes, "Adult". Else, "Minor".
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"// This is legal but horrible for readability
const result = score > 90 ? "A" : score > 80 ? "B" : "C";Common Pitfalls
- Nesting ternary operators. While you can technically chain
a ? b : c ? d : e, it becomes completely unreadable. If you need more than two outcomes, use standardif/elseor aswitchstatement.
Interview Questions
if statement?JSX requires expressions (which evaluate to a value). An if/else is a statement (an action). Because the ternary operator evaluates to a value, it can be embedded directly inside JSX {} blocks.
Real-World Example
Conditionally applying CSS classes in React based on a state variable.
return (
<button className={isActive ? 'btn-active' : 'btn-disabled'}>
Click Me
</button>
);Check Your Knowledge
Test your understanding of Ternary Operator with these quick questions.