{module 5}
Functions
Your first JavaScript20 min read
What you will be able to do
- Write a function that takes values as parameters and returns a result.
- Keep money in whole cents, and explain why decimal dollars go wrong.
- Show an amount in cents as dollars with
Intl.NumberFormat.
Why it matters
Montevideo Bookbinders repairs and binds books in Montevideo, Uruguay. A new spine for a book costs $4.35. Valentina, the owner, had a page that worked out the price of several repairs. A customer with three books saw "$13.049999999999999" and wrote to ask whether the shop was trying to trick her. Then the price went up, and Valentina's helper Martín changed it in two places in the script and missed the third.
Both problems have the same kind of fix. Keep each price in one place, give each calculation a name, and work with money in a way that never produces a fraction of a cent.
The idea
A function names a calculation
In lesson 1, showTotal was a function: a set of steps with a name. A function can also take values in and give a result back, like a calculation on paper: "the price of some repairs is the number of books times $4.35".
function totalRepairCents(books) {
return books * repairCents;
}functionstarts the function, andtotalRepairCentsis its name.books, in the round brackets, is a parameter: a name for a value that the function receives each time it runs.returngives a result back and ends the function.
To call a function means to run it. You write its name, then the value for the parameter in brackets:
const normalCents = totalRepairCents(books);The value in the brackets is called an argument. If books is 3, the function runs with its parameter set to 3, works out 3 times 435, and returns 1305. That result is stored in normalCents.
A function can have several parameters, with commas between them. Lesson 1's showTotal had none, so its brackets were empty.
Why not dollars
Make a page called decimals.html like values.html in lesson 2, with a script element for decimals.js. The script prints three sums in the Console:
console.log(0.1 + 0.2);
console.log(3 * 4.35);
console.log(3 * 435);0.30000000000000004
13.049999999999999
1305The first two lines are wrong. A computer stores numbers in binary, with only the digits 0 and 1, and most decimal fractions cannot be stored exactly that way. One third cannot be written exactly in decimal either: 0.333 has to stop somewhere. JavaScript stores the nearest number it can, and a small error appears when you calculate. Whole numbers are stored exactly, so the third line is right.
So a script keeps money as a whole number of cents, the smallest unit of the dollar. $4.35 is 435. Put the unit in the name, as in repairCents, so nobody mixes dollars with cents. Adding, subtracting and multiplying whole numbers always gives a whole number.
Rounding a share
A percentage can still leave a fraction. 25% of 435 cents is 108.75 cents. Math.round() gives the nearest whole number, and a half goes up:
function withRushCents(cents) {
return cents + Math.round((cents * rushPercent) / 100);
}Multiply first and divide by 100 last, then round once, at the step that makes the fraction.
Showing cents as dollars
Customers read dollars, so the script turns cents into text only at the end, when it shows them. JavaScript has a built-in formatter for this:
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });new Intl.NumberFormat(...) makes a formatter. "en-US" asks for numbers written the way they are in the United States. The part in curly brackets gives two settings: show a currency, and the currency is US dollars. Words in curly brackets with colons like this are called an object. Lesson 5 uses objects for data.
The formatter has a function of its own, format, which turns a number of dollars into text:
function formatCents(cents) {
return dollars.format(cents / 100);
}formatCents(1305) returns "$13.05", with the dollar sign, two decimal places and a comma in large amounts. Dividing by 100 is safe here because the result is only shown. Nothing is calculated from it.
Worked example
Create index.html, styles.css and prices.js in a new folder and save them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Spine repair prices, Montevideo Bookbinders</title>
<link rel="stylesheet" href="styles.css" />
<script src="prices.js" defer></script>
</head>
<body>
<main>
<h1>Montevideo Bookbinders</h1>
<p>We repair the spine of a book for $4.35. In a hurry? Two-day service costs 25% more.</p>
<label for="books">How many books?</label>
<input type="number" id="books" value="1" />
<p id="normal">Ready in 10 days: $4.35</p>
<p id="rush">Ready in 2 days: $5.44</p>
</main>
</body>
</html>body {
max-width: 40rem;
margin: 0 auto;
padding: 1rem;
font-family: Arial, sans-serif;
line-height: 1.5;
}
#normal,
#rush {
font-weight: bold;
}// Prices are in cents. Change them here and nowhere else.
const repairCents = 435;
const rushPercent = 25;
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const booksField = document.querySelector("#books");
const normal = document.querySelector("#normal");
const rush = document.querySelector("#rush");
function totalRepairCents(books) {
return books * repairCents;
}
function withRushCents(cents) {
return cents + Math.round((cents * rushPercent) / 100);
}
function formatCents(cents) {
return dollars.format(cents / 100);
}
function showPrices() {
const books = Number(booksField.value);
const normalCents = totalRepairCents(books);
normal.textContent = `Ready in 10 days: ${formatCents(normalCents)}`;
rush.textContent = `Ready in 2 days: ${formatCents(withRushCents(normalCents))}`;
}
booksField.addEventListener("input", showPrices);Open the page and type 3:
Ready in 10 days: $13.05
Ready in 2 days: $16.31Check it by hand. 3 times 435 is 1305 cents. A quarter of 1305 is 326.25, which rounds to 326, and 1305 plus 326 is 1631 cents. Now type 250, for a library:
Ready in 10 days: $1,087.50
Ready in 2 days: $1,359.38The formatter added the comma and kept two decimal places.
Read prices.js from the top. Line 1 is a comment: a line that starts with //, which the browser ignores. It is a note for the next person. Lines 2 and 3 are the only places the prices appear. Line 5 makes the formatter once. Lines 10 to 20 are three small functions, each with one job and a name that says what it returns. showPrices, on lines 22 to 27, calls them and writes the results on the page.
The last line of showPrices calls one function inside another. withRushCents(normalCents) runs first and returns 1631, and formatCents turns that into "$16.31".
Common mistakes
Forgetting return
function totalRepairCents(books) {
books * repairCents;
}Type 3:
Ready in 10 days: $NaN
Ready in 2 days: $NaNThere is no error. The function worked out 1305 and then threw it away. A function without return gives back undefined, and undefined / 100 is NaN. When a function's result is NaN or undefined, look for its return.
Showing cents as if they were dollars
function formatCents(cents) {
return dollars.format(cents);
}Ready in 10 days: $1,305.00
Ready in 2 days: $1,631.00The formatter expects dollars and was given cents, so every price is 100 times too large. A customer may laugh at this one. Another may pay it. Divide by 100 in one place only: inside formatCents.
A formatter without a currency
const dollars = new Intl.NumberFormat("en-US", { style: "currency" });Type 3. The prices do not change, and the Console shows:
Ready in 10 days: $4.35
Ready in 2 days: $5.44
page error: Uncaught TypeError: Currency code is required with currency style.The message says what is missing. style: "currency" needs a currency setting, because the formatter cannot guess which currency you mean. The error happens on line 5, when the page opens, so the script stops there and the listener is never added. Add currency: "USD".
Think it through
Priya prints posters for $2.75 each, with $4 delivery for any order. She wants a function that returns the total in cents for a number of posters.
Understand. In: a number of posters. Out: a whole number of cents. Every order pays the delivery once.
Break down. The price of the posters. The delivery. The total. Showing it in dollars is a separate job.
Plan. Two const values at the top: posterCents = 275 and deliveryCents = 400. A function orderCents(posters) that returns posters times 275, plus 400. The existing formatCents shows the result.
Build. She writes the function, adds console.log(orderCents(2)) at the end of the script, and reloads. The Console shows 950.
Test. By hand, two posters are $5.50, plus $4, which is $9.50. That matches 950 cents. The odd case is 0 posters. The function returns 400, so a customer would pay $4.00 for nothing. That is a decision, not a sum, so she notes it for lesson 4.
Reflect. Because the function returns a number and does not touch the page, one console.log line was enough to test it. She will keep calculations and page changes in separate functions.
At work
The person who changes a price next year may not be you, and may not be a developer. A README should say exactly where each price lives, in which file, on which line, and in which unit.
Martín added this section to the README for Valentina:
How to change a price
All prices are at the top of
prices.js, on lines 2 and 3. They are in cents, so $4.35 is written435.
repairCentsis the price of one spine repair.rushPercentis how much more the two-day service costs, as a percentage.Change the number, save the file, and reload the page to check it. Then change
index.htmltoo: the sentence that gives the price on line 13, and the two amounts on lines 16 and 17, which the page shows before anyone types.
The last paragraph matters. The page states the price in the script and in the HTML, and the README admits it. A good handover note does not pretend that a project is tidier than it is.
Your tasks
Task 1: Build the price page
Create the three files and type 3, then 250.
You are done when your page shows the four amounts from the worked example, and you can work out the rush price for 3 books by hand.
Task 2: Break the return
Remove return from totalRepairCents, type a number, and read the page. Then put it back. Do the same with the / 100 in formatCents.
You are done when you have seen $NaN and $1,305.00 on your own page, and you can say which mistake gave which.
Task 3: Gift wrapping
Valentina offers gift wrapping at $1.90 a book. Add a third line: "Ready in 10 days, gift wrapped: $18.75" for 3 books. Write a new function that takes the number of books and returns the wrapping in cents. Do not change the other functions.
You are done when 3 books shows $18.75 on the new line, 0 books shows $0.00, and the price of wrapping appears once in your script.
Recap
- A function names a calculation. Parameters bring values in, and
returngives the result back. - Decimal fractions are not stored exactly, so
0.1 + 0.2is not 0.3. Keep money in whole cents. Math.round()rounds a share of a price to whole cents, once.new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })makes a formatter. Divide cents by 100 only when you format.- Keep each price in one named
const, and say in the README where it is.
Go deeper
- MDN: Functions, reusable blocks of code explains functions, parameters and arguments for beginners.
- MDN: return shows what a function gives back with and without
return. - MDN: Math.round() says how halves are rounded.
- MDN: Intl.NumberFormat() constructor lists the settings, including
styleandcurrency.