Lesson 7 of 11
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.
The parts of a function
This lesson is about writing functions. The calculator gives you four functions to write.
function add(a, b) {
return a + b;
}addis the name. You use it to call the function later.aandbare the parameters. They hold the two numbers you give the function when you call it.returnsends the answer back out. It also ends the function right away. No code 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 sits on the screen. No other code can use it. A function that returns its answer gives the value back to you. You can store it, do more maths on it, or pass it into another function.
Open the console with F12. Try these three lines. The second and third lines 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 this 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. Test them on their own. Connect them to the page after that.
Make the page
Make
calculator.html. It needs two boxes, an operator<select>, an equals button, and an empty<p id="result">. Linkcalculator.cssin the head. Linkcalculator.jsat the end of the body. Open the page. The controls show, but nothing happens.Write add, and test it alone
In
calculator.js, writeadd(a, b). Do not change the page yet. Reload the page and open the console. Typeadd(2, 3). You should get5back. Get a function working on its own before you connect it to anything. That is a good habit to build.Write the other three
Write
subtract,multiply, anddivide. Test each one in the console. They are all the same shape asadd.Connect the button
Write
calculate(). Read both boxes and useparseFloaton them. Read the operator. Then use aswitchto call the right function. Put the returned answer in#result. Connectcalculate()to the button withaddEventListener. It now works for normal input. It goes wrong 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. This check belongs here, in the page code. It does not belong 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 changes in the files beside this guide. Each one only uses what this lesson has already covered. Tick each one when it works.
Check yourself
Three quick questions on this lesson. Get them all right to finish the lesson and earn a pack.
Loading your answers
Teacher's versionHow to run this lesson, what to check, and any answers. Students do not need this.
How to teach it
- Step 2 is the important one. Write
addand stop there. Call it from the console together, several times, with different numbers. Do this before anything is connected to the page. A student who has seen a function answer a question in the console already understandsreturn. - Then run the three console lines from Why return matters together.
add(2, 3) * 10is the line that makes the idea clear. It gives back an answer you can keep using. - The
console.logexperiment teaches more than any explanation. One word changes, and the page saysundefined. Let the student make the change and read the result themselves. - Have them write
subtractwithout help. If they can, they understand the shape of a function. 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 good arguments both ways. That conversation is software design.