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
. The starter provides:
temperature = 25score = 85stock = 0
Use the ternary operator to create:
weatherDescriptionβ"hot"iftemperature > 30, otherwise"comfortable"passedβtrueifscore >= 70, otherwisefalsestockMessageβ"In stock"ifstock > 0, otherwise"Out of stock"
Export all three.
Required exports
weatherDescription, passed, stockMessageCompletion criteria
Each export follows the ternary rules above for the given fixtures. Log or
inspect the values to confirmβdon't hardcode answers that ignore the conditions.
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.