AI Hints
Home›JavaScript Tutorial›Callbacks and Recursion
JavaScript · Lesson 38 of 138

Practice: A Tip Calculator

Functions together.

⏱ 2 min read▶ Video at 45:43🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Practice: A Tip Calculator
From the video: Practice: A Tip Calculator
  • 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.

app.jsjavascript
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));
Output
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.

keyvalue
tip()one job
split()one job
summary()combines them
Habitone 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
Next up: Recursion — functions calling themselves