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:
  1. The condition to check
  2. The value if the condition is true (after ?)
  3. 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
index.ts
. The starter provides:
  • temperature = 25
  • score = 85
  • stock = 0
Use the ternary operator to create:
  1. weatherDescription β€” "hot" if temperature > 30, otherwise "comfortable"
  2. passed β€” true if score >= 70, otherwise false
  3. stockMessage β€” "In stock" if stock > 0, otherwise "Out of stock"
Export all three.

Required exports

weatherDescription, passed, stockMessage

Completion 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.

Please set the playground first

Loading "Ternary Operator"
Loading "Ternary Operator"
Login to get access to the exclusive discord channel.
Loading Discord Posts