Ternary Operator
Ternary Operator
π¨βπΌ Sometimes you need to choose between two values based on a condition. The
if/else statement works, but it's verbose when you just need a simple
choice.The ternary operator is a concise way to choose between two values:
const result = condition ? valueIfTrue : valueIfFalse
It's called "ternary" because it has three parts:
- The condition to check
- The value if the condition is true (after
?) - The value if the condition is false (after
:)
Compare these equivalent approaches:
// Using if/else (5 lines)
let status: string
if (age >= 18) {
status = 'adult'
} else {
status = 'minor'
}
// Using ternary (1 line)
const status = age >= 18 ? 'adult' : 'minor'
π¨ Open
and use the ternary operator to:
- Create
weatherDescription- "hot" if temperature > 30, otherwise "comfortable" - Create
passed- true if score >= 70, otherwise false - Create
stockMessage- "In stock" if stock > 0, otherwise "Out of stock"
The ternary operator is an expression that produces a value, while
if/else is a statement that executes code. This means you can use
ternaries anywhere you need a valueβin variable assignments, function
arguments, or template literals.

