Basic Web Development

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

  1. Type a number in the first box.
  2. Choose an operator from the dropdown.
  3. Type a number in the second box.
  4. 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.

calculator.js
function add(a, b) {
    return a + b;
}
  • add is the name. You use it to call the function later.
  • a and b are the parameters. They are empty boxes that get filled with the numbers you hand over.
  • return sends 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))    // 20

Choosing 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.

calculator.js — the switch picks one function
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.

  1. Make the page

    Make calculator.html with two boxes, an operator <select>, an equals button, and an empty <p id="result">. Link calculator.css in the head and calculator.js at the end of the body. Open it. The controls show, but nothing happens.

  2. Write add, and test it alone

    In calculator.js, write add(a, b). Do not touch the page yet. Reload, open the console, and type add(2, 3). You should get 5 back. Getting a function right on its own, before it is wired to anything, is a habit worth building.

  3. Write the other three

    Write subtract, multiply, and divide. Test each one in the console. They are all the same shape as add.

  4. Wire up the button

    Write calculate(). Read both boxes, use parseFloat on them, read the operator, then use a switch to call the right function. Put the returned answer in #result. Connect it with addEventListener. It now works for normal input, and misbehaves on bad input. That is expected for now.

  5. Check for non-numbers

    Add an isNaN check on both numbers at the top of calculate(). If either one fails, show a message and return early.

  6. Check for divide by zero

    Inside the "/" case, check whether the second number is 0. If it is, show a message and stop. Notice that this check belongs here, in the page code, and not inside divide.

  7. Check the operator

    Add a default case 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 add and 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 understands return already.
  • Then run the three console lines from Why return matters together. add(2, 3) * 10 is the moment the idea lands — an answer you can keep using.
  • The console.log experiment is worth more than any explanation. One word changed, and the page says undefined. Let the student make the change and read the result themselves.
  • Have them write subtract without 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 in divide(). Ask where it belongs and why. There are decent arguments both ways, and that conversation is software design.