Problem Description
Let's write a function getTicketPrice(age) that takes a person's age.
If the person is
18or older, the price is$20.If the person is younger than
18, the price is$10.
Constraint: You must use the ternary operator to solve this.
Test Cases:
getTicketPrice(30)should return$20getTicketPrice(18)should return$20getTicketPrice(10)should return$10
💡 The 'Syntax Nudge'
Your "condition" will be age >= 18. Your "valueIfTrue" will be $20. Your "valueIfFalse" will be $10.
How do you assemble these three parts using the ? : syntax?
The Ternary (? :)
This operator is a "ternary" because it works on three operands. It's our final operator in this bootcamp.
It's just a clean, one-line shortcut for a simple if...else statement.
The if...else way:
let message;
if (age >= 21) {
message = "You may enter.";
} else {
message = "You are too young.";
}
The Ternary way:
let message = (age >= 21) ? "You may enter." : "You are too young.";
The syntax is: (condition) ? valueIfTrue : valueIfFalse