Lesson 7 of 10
Calculator
Write one function for each operation. Each one takes two numbers and gives an answer back.
What you will learn
- Writing a function
- Parameters
- return
- Calling a function
- parseFloat
- switch
- isNaN
Before you start
Mad Libs. You have written code that runs when a button is clicked. Here you write functions of your own and call them by name.
What this page does
- Type a number in the first box.
- Choose an operator from the dropdown.
- Type a number in the second box.
- Click the equals button. The answer appears below.
Now try to break it. Leave a box empty. Type letters. Divide by zero. The page shows a message instead of a wrong answer.
A function is a named recipe
This lesson is really about writing functions. The calculator is just a good excuse to write four of them.
function add(a, b) {
return a + b;
}addis the name. You use it to call the function later.aandbare the parameters. They are empty boxes that get filled with the numbers you hand over.returnsends the answer back out. It also ends the function straight away, so nothing after it runs.
The other three follow the same shape. Only the maths in the middle changes.
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
return a / b;
}Why return matters
A function that shows its answer is finished with it. The value is on the screen and nothing else can use it. A function that returns its answer hands the value back. You can store it, do more maths on it, or pass it into another function.
Open the console with F12 and try these three lines. The second and third only work because add returns a value.
add(2, 3) // 5
add(2, 3) * 10 // 50
multiply(10, add(1, 1)) // 20Choosing which function to call
calculate() does no maths at all. It has four jobs, in order: read the boxes, check them, call the right function, and show what came back.
switch (operator) {
case "+": answer = add(num1, num2); break;
case "-": answer = subtract(num1, num2); break;
case "*": answer = multiply(num1, num2); break;
case "/": answer = divide(num1, num2); break;
}Build it step by step
Write the functions first and test them on their own. Wire up the page after.
Make the page
Make
calculator.htmlwith two boxes, an operator<select>, an equals button, and an empty<p id="result">. Linkcalculator.cssin the head andcalculator.jsat the end of the body. Open it. The controls show, but nothing happens.Write add, and test it alone
In
calculator.js, writeadd(a, b). Do not touch the page yet. Reload, open the console, and typeadd(2, 3). You should get5back. Getting a function right on its own, before it is wired to anything, is a habit worth building.Write the other three
Write
subtract,multiply, anddivide. Test each one in the console. They are all the same shape asadd.Wire up the button
Write
calculate(). Read both boxes, useparseFloaton them, read the operator, then use aswitchto call the right function. Put the returned answer in#result. Connect it withaddEventListener. It now works for normal input, and misbehaves on bad input. That is expected for now.Check for non-numbers
Add an
isNaNcheck on both numbers at the top ofcalculate(). If either one fails, show a message andreturnearly.Check for divide by zero
Inside the
"/"case, check whether the second number is0. If it is, show a message and stop. Notice that this check belongs here, in the page code, and not insidedivide.Check the operator
Add a
defaultcase to the switch. It runs when the operator is not one the code knows.
Try these changes
Make these in the files beside this guide. None of them need anything the lesson has not covered.
- Write `power(a, b)` that multiplies `a` by itself `b` times. Add a `^` option to the dropdown and the switch.
- Write `double(n)` that returns `n * 2`. Predict what `double(3) + double(5)` gives, then check in the console.
- Work out `(5 + 3) * (10 - 4)` in the console using only your four functions.
- Show the whole sum, such as `3 + 4 = 7`, instead of only the answer.
- Show the messages on the page instead of in a pop-up box.
- Make the Enter key run the calculation.
Teacher's versionHow to run this lesson, what to check, and any answers. Students do not need this.
How to teach it
- Step 2 carries the lesson. Write
addand stop. Call it from the console together, several times, with different numbers, before anything is connected to the page. A student who has seen a function answer a question in the console understandsreturnalready. - Then run the three console lines from Why return matters together.
add(2, 3) * 10is the moment the idea lands — an answer you can keep using. - The
console.logexperiment is worth more than any explanation. One word changed, and the page saysundefined. Let the student make the change and read the result themselves. - Have them write
subtractwithout help. If they can, the shape of a function has landed and the rest of the lesson is typing. - The divide-by-zero check sits in
calculate(), not individe(). Ask where it belongs and why. There are decent arguments both ways, and that conversation is software design.