Skip to content

Ternary Operator

The ternary operator is a shorthand for if-else statements. It takes three operands and returns one of two values based on a condition.

condition ? expressionIfTrue : expressionIfFalse;
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
// status: 'Adult'
flowchart TD
Condition["age >= 18 ?"]
Condition -->|true| True["'Adult'"]
Condition -->|false| False["'Minor'"]
const score = 85;
const grade = score >= 90 ? 'A'
: score >= 80 ? 'B'
: score >= 70 ? 'C'
: 'F';
// grade: 'B'
  • Use for simple conditional assignments
  • Avoid deeply nested ternary operators (max 2 levels)
  • Use if-else for complex logic
  • Shorthand for if-else
  • Returns a value, so it can be used in expressions
  • Keep it simple and readable