edubun
English
1 / 13

12 / 12 · Intro

Project: tip calculator and FizzBuzz

A bill of 84 with a 20 percent tip split four ways comes to 25.20 each. This unit builds that calculator, then the classic FizzBuzz exercise, from the pieces in earlier units.

Jump to the 10 practice questions

You will learn

  • Turn a problem into named inputs, steps and outputs
  • Show money with toFixed and wrap the work in a function
  • Write FizzBuzz with the narrowest condition first

Before this: Objects

1Explain

Step 1: the calculation

Check the numbers by hand before trusting the code: 20 percent of 84 is 16.8, the total is 100.8, and 100.8 divided by 4 is 25.2. Testing with values whose answer you already know is how you catch mistakes such as a rate typed as 20 instead of 0.2, which would make the tip 1,680.

Each line names one step: tip, then total, then each person's share.

  1. const bill = 84;
  2. const rate = 0.2;
  3. const people = 4;
  4. const tip = bill * rate; // 16.8
  5. const total = bill + tip; // 100.8
  6. const each = total / people; // 25.2
Variables
Output

2Explore

Change the bill and the rate

Money is normally shown with two decimal places, and printing 25.2 looks unfinished. The number method toFixed(2) returns a string with exactly two decimals, so each.toFixed(2) gives "25.20". Remember from the numbers unit that decimals can carry tiny binary rounding errors; toFixed also hides those, which is another reason to use it for display.

toFixed(2) always shows two decimal places, so every share prints like money.

bill
tip rate
const bill = 84;
const rate = 0.2;
const people = 4;
const each = (bill * (1 + rate)) / people;
console.log(each.toFixed(2));
Output
25.20

3Problem

Two decimal places

What does this print?
console.log((25.2).toFixed(2));

Hint

toFixed keeps the trailing zero.

Solution

Answer: 25.20

toFixed(2) always shows two decimal places.

4Explain

Step 3: wrap it in a function

A calculation you might run again with other numbers belongs in a function. The function below returns an object, so a single call can hand back all three results with clear names. Default parameters make the usual case short to write.

The call opens a box "inside splitBill()". It returns one object with three results.

  1. function splitBill(bill, rate = 0.15, people = 1) {
  2. const tip = bill * rate;
  3. const total = bill + tip;
  4. return { tip, total, each: total / people };
  5. }
  6. const r = splitBill(84, 0.2, 4);
  7. console.log(`Tip: ${r.tip.toFixed(2)}`); // Tip: 16.80
  8. console.log(`Each: ${r.each.toFixed(2)}`); // Each: 25.20
Variables
Output
Tip: 16.80
Each: 25.20

5Problem

Shorthand properties

What does this print?

const tip = 4;
const total = 24;
const r = { tip, total };
console.log(r.total - r.tip);

Hint

{ tip, total } means { tip: tip, total: total }.

Solution

Answer: 20

{ tip, total } is { tip: 4, total: 24 }, and 24 - 4 = 20.

6Explain

FizzBuzz

FizzBuzz is a counting game turned into a programming exercise. Count from 1 to 15. For multiples of 3 say Fizz, for multiples of 5 say Buzz, for multiples of both say FizzBuzz, and otherwise say the number. It uses a loop, the remainder operator and an if chain, and it has one trap. The number 15 is a multiple of 3, so if you test for 3 first, 15 prints Fizz and never reaches the FizzBuzz branch.

Watch the branch each number takes: 15 is checked first, then 3, then 5.

  1. for (let i = 1; i <= 15; i++) {
  2. if (i % 15 === 0) {
  3. console.log("FizzBuzz");
  4. } else if (i % 3 === 0) {
  5. console.log("Fizz");
  6. } else if (i % 5 === 0) {
  7. console.log("Buzz");
  8. } else {
  9. console.log(i);
  10. }
  11. }
Variables
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

7Problem

The FizzBuzz trap

What does this print?
const i = 15;
if (i % 3 === 0) {
  console.log("Fizz");
} else if (i % 15 === 0) {
  console.log("FizzBuzz");
}

Hint

Which condition is checked first for 15?

Solution

Answer: Fizz

The first true condition wins, and 15 % 3 === 0 is checked first. That is the FizzBuzz trap.

8Problem

How many Fizz?

How many of the numbers 1 to 15 print as Fizz (not FizzBuzz)?

Hint

List the multiples of 3 up to 15 and remove the one that is also a multiple of 5.

Solution

Answer: 4

3, 6, 9 and 12. 15 prints FizzBuzz.

9Practice

Tip calculator

Replace the three zeros with calculations so the output is Tip: 16.80, Total: 100.80 and Each: 25.20.

Expected output
Tip: 16.80
Total: 100.80
Each: 25.20
Your code
const bill = 84;
const rate = 0.2;
const people = 4;

const tip = 0;
const total = 0;
const each = 0;

console.log(`Tip: ${tip.toFixed(2)}`);
console.log(`Total: ${total.toFixed(2)}`);
console.log(`Each: ${each.toFixed(2)}`);
Hint

tip = bill * rate, total = bill + tip, each = total / people.

A solution
const bill = 84;
const rate = 0.2;
const people = 4;

const tip = bill * rate;
const total = bill + tip;
const each = total / people;

console.log(`Tip: ${tip.toFixed(2)}`);
console.log(`Total: ${total.toFixed(2)}`);
console.log(`Each: ${each.toFixed(2)}`);

10Practice

Write FizzBuzz yourself

Turn this counter into FizzBuzz: Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, the number otherwise.

Expected output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Your code
for (let i = 1; i <= 15; i++) {
  console.log(i);
}
Hint

Test i % 15 === 0 first; otherwise 15 is caught by the test for 3.

A solution
for (let i = 1; i <= 15; i++) {
  if (i % 15 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

11Practice

Spending by kind

Finish totalFor with a loop and an if, so the program prints food 24 and travel 15.

Expected output
food 24
travel 15
Your code
const expenses = [
  { what: "lunch", kind: "food", cost: 9 },
  { what: "bus", kind: "travel", cost: 3 },
  { what: "dinner", kind: "food", cost: 15 },
  { what: "taxi", kind: "travel", cost: 12 },
];

function totalFor(kind) {
  let sum = 0;
  // Add the cost of every expense
  // whose kind matches.
  return sum;
}

console.log("food", totalFor("food"));
console.log("travel", totalFor("travel"));
Hint

Loop over expenses and add e.cost only when e.kind === kind.

A solution
const expenses = [
  { what: "lunch", kind: "food", cost: 9 },
  { what: "bus", kind: "travel", cost: 3 },
  { what: "dinner", kind: "food", cost: 15 },
  { what: "taxi", kind: "travel", cost: 12 },
];

function totalFor(kind) {
  let sum = 0;
  for (const e of expenses) {
    if (e.kind === kind) sum += e.cost;
  }
  return sum;
}

console.log("food", totalFor("food"));
console.log("travel", totalFor("travel"));

12Explain

Common mistakes

const each = "25.2";
console.log(each.toFixed(2));
Error message
TypeError: each.toFixed is not a function (line 2)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. The line number shows where the program stopped. A SyntaxError stops it before any line runs.

toFixed belongs to numbers, and "25.2" is a string. Calculate with numbers and call toFixed only when printing; toFixed itself returns a string.

13

Summary

  • Name the inputs and outputs first, then the steps between them.
  • Check with values whose answers you know.
  • Calculate with numbers; use toFixed(2) only when printing.
  • Wrap reusable work in a function; return an object for several results.
  • FizzBuzz: test the narrowest case (multiples of 15) first.

Back to the courseJavaScript
Full text · The whole lesson as one text

From a problem to a program

A tip calculator turns a bill, a tip rate and a number of people into each person’s share. Writing a program starts before any code. First say in plain words what goes in, what comes out, and what happens in between. For a tip calculator, the inputs are the bill, the tip rate and the number of people. The outputs are the tip, the total and each person's share. In between there are three small calculations. Writing this down turns one vague task into several small ones, each of which you already know how to do.

Step 1: the calculation

const bill = 84;
const rate = 0.2;
const people = 4;

const tip = bill * rate;          // 16.8
const total = bill + tip;         // 100.8
const each = total / people;      // 25.2

Check the numbers by hand before trusting the code: 20 percent of 84 is 16.8, the total is 100.8, and 100.8 divided by 4 is 25.2. Testing with values whose answer you already know is how you catch mistakes such as a rate typed as 20 instead of 0.2, which would make the tip 1,680.

Step 2: showing money properly

Money is normally shown with two decimal places, and printing 25.2 looks unfinished. The number method toFixed(2) returns a string with exactly two decimals, so each.toFixed(2) gives "25.20". Remember from the numbers unit that decimals can carry tiny binary rounding errors; toFixed also hides those, which is another reason to use it for display. Keep the numbers as numbers while calculating and call toFixed only at the very end, when printing.

Step 3: wrap it in a function

A calculation you might run again with other numbers belongs in a function. The function below returns an object, so a single call can hand back all three results with clear names. Default parameters make the usual case short to write.

function splitBill(bill, rate = 0.15, people = 1) {
  const tip = bill * rate;
  const total = bill + tip;
  return { tip, total, each: total / people };
}

const r = splitBill(84, 0.2, 4);
console.log(`Tip: ${r.tip.toFixed(2)}`);       // Tip: 16.80
console.log(`Each: ${r.each.toFixed(2)}`);     // Each: 25.20

The line return { tip, total, each: total / people }; uses a shorthand: writing tip alone inside an object means tip: tip, a property whose key and variable share a name.

FizzBuzz

FizzBuzz is a counting game turned into a programming exercise. Count from 1 to 15. For multiples of 3 say Fizz, for multiples of 5 say Buzz, for multiples of both say FizzBuzz, and otherwise say the number. It uses a loop, the remainder operator and an if chain, and it has one trap. The number 15 is a multiple of 3, so if you test for 3 first, 15 prints Fizz and never reaches the FizzBuzz branch. The fix is the rule from the if unit: put the narrowest condition first.

for (let i = 1; i <= 15; i++) {
  if (i % 15 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

Testing i % 15 === 0 works because a number divisible by both 3 and 5 is divisible by 15. Writing i % 3 === 0 && i % 5 === 0 says the same thing more directly, and either is fine. When your version runs, compare its output line by line with the expected list: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz.

What to build next

You now have the core of the language: values, variables, operators, decisions, loops, arrays, functions and objects. Almost every program is built from these pieces. Good next steps are to rewrite FizzBuzz as a function that takes the upper limit, or to make the tip calculator round each share up to whole currency units with Math.ceil. Another is to keep a list of expenses in an array of objects and print a total by category. The MDN JavaScript Guide, which this course follows, continues with topics such as collections, classes and working with web pages.

Key points
  • Name the inputs and outputs first, then the steps between them.
  • Check with values whose answers you know.
  • Calculate with numbers; use toFixed(2) only when printing.
  • Wrap reusable work in a function; return an object for several results.
  • FizzBuzz: test the narrowest case (multiples of 15) first.

Practice questions from Project: tip calculator and FizzBuzz on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (2)
  • MDN Web Docs, JavaScript Guide (developer.mozilla.org/en-US/docs/Web/JavaScript/Guide, chapters Introduction, Grammar and types, Control flow, Loops and iteration, Functions, Expressions and operators, Numbers and strings, Indexed collections, Working with objects; checked 2026-10-17)
  • Ecma International, ECMA-262 ECMAScript 2026 Language Specification, 17th edition, June 2026 (tc39.es/ecma262 and ecma-international.org/publications-and-standards/standards/ecma-262, checked 2026-10-17).

Checked: 2026-10-17