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 questionsYou 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.
const bill = 84;const rate = 0.2;const people = 4;const tip = bill * rate; // 16.8const total = bill + tip; // 100.8const each = total / people; // 25.2
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.
const bill = 84;
const rate = 0.2;
const people = 4;
const each = (bill * (1 + rate)) / people;
console.log(each.toFixed(2));25.203Problem
Two decimal places
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.
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.80console.log(`Each: ${r.each.toFixed(2)}`); // Each: 25.20
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.
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);}}
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
7Problem
The FizzBuzz trap
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.
Tip: 16.80
Total: 100.80
Each: 25.20const 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.
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzfor (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.
food 24
travel 15const 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));TypeError: each.toFixed is not a function (line 2)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- 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.