JavaScript Project: Rule-Based Ticket Pricing
Quick answer
A small pricing function combines validation and ordered branching. Define the accepted inputs and exact boundary rules before writing the code.
How it works
For this project, age must be a safe integer from 0 to 120. Return -1 for invalid input, 0 under age 6, 5 for ages 6–17, 7 from age 65, and 12 otherwise. A guard rejects invalid input before price decisions. Return a number in every branch; no taxes, currencies or discounts outside these invented practice rules are implied.
function ticket(age) { if (!Number.isSafeInteger(age) || age < 0 || age > 120) { return -1; } if (age < 6) { return 0; } if (age < 18) { return 5; } if (age >= 65) { return 7; } return 12;}console.log(ticket(5), ticket(6), ticket(18), ticket(65));Expected output in Node.js:
0 5 12 7The boundary values verify all four price categories.
function ticket(age) { if (!Number.isSafeInteger(age) || age < 0 || age > 120) { return -1; } if (age < 6) { return 0; } if (age < 18) { return 5; } if (age >= 65) { return 7; } return 12;}console.log(ticket(-1), ticket("6"), ticket(120), ticket(121));Expected output in Node.js:
-1 -1 7 -1Invalid ages and text are rejected; 120 is a valid senior age.
Common mistakes
Check the values immediately before and after each boundary. A broad adult condition before the senior condition can accidentally hide the senior branch.
Practice
Implement the ticket function and test every stated boundary and invalid type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Project: Rule-Based Ticket Pricing — Knowledge Check
Apply the taught concept and reason about the result.
What price does the project return for age 6?
What price does the project return for age 17?
What price does the project return for age 65?
What does the project return for the string "6"?
Why test ages 5 and 6 separately?