Practice: A Tip Calculator
Functions together.
Let's build a tip calculator from small functions. Given a bill, a tip percentage, and the number of people, work out the tip, the total, and how much each person pays. Each step gets its own little function.

- Bill, tip, people
- Tip, total, per person
- Small functions
Building it up
Tip takes a bill and a percent. Split divides a total between people. Then summary uses both, and returns a neat line of text, with two decimal places. Each function does one thing, so each is easy to check. Run it.
const tip = (bill, percent = 15) => bill * percent / 100;
const split = (total, people) => total / people;
function summary(bill, percent, people) {
const t = tip(bill, percent);
const total = bill + t;
const each = split(total, people);
return `Tip $${t.toFixed(2)}, total $${total.toFixed(2)}, each $${each.toFixed(2)}`;
}
console.log(summary(80, 15, 4));
console.log(summary(120, 20, 3));Tip $12.00, total $92.00, each $23.00 Tip $24.00, total $144.00, each $48.00
Small functions win
Breaking a problem into small functions makes it easier to write, test, and change. If the restaurant changes how tips work, you only change one function. This habit, one function, one job, is one of the best things you can learn as a programmer.
| key | value |
|---|---|
| tip() | one job |
| split() | one job |
| summary() | combines them |
| Habit | one function, one job |
Summary
We built a tip calculator from small functions, each with one job. Next, functions that call themselves, recursion.
Key takeaways- Small helpers
- Combine them
- One job each