Ternary Operator
Ternary Operator (Conditional Operator)
Section titled “Ternary Operator (Conditional Operator)”Introduction
Section titled “Introduction”The ternary operator is a shorthand for if-else statements. It takes three operands and returns one of two values based on a condition.
Syntax
Section titled “Syntax”condition ? expressionIfTrue : expressionIfFalse;Example
Section titled “Example”const age = 20;const status = age >= 18 ? 'Adult' : 'Minor';// status: 'Adult'Visual Explanation
Section titled “Visual Explanation”flowchart TD Condition["age >= 18 ?"] Condition -->|true| True["'Adult'"] Condition -->|false| False["'Minor'"]Chaining
Section titled “Chaining”const score = 85;const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';// grade: 'B'Best Practices
Section titled “Best Practices”- Use for simple conditional assignments
- Avoid deeply nested ternary operators (max 2 levels)
- Use
if-elsefor complex logic
Summary
Section titled “Summary”- Shorthand for
if-else - Returns a value, so it can be used in expressions
- Keep it simple and readable