Skip to main content
← JavaScript

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

  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.

The parts of a function

This lesson is about writing functions. The calculator gives you four functions to write.

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 hold the two numbers you give the function when you call it.
  • return sends 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))    // 20

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

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. Test them on their own. Connect them to the page after that.

  1. Make the page

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

  2. Write add, and test it alone

    In calculator.js, write add(a, b). Do not change the page yet. Reload the page and open the console. Type add(2, 3). You should get 5 back. Get a function working on its own before you connect it to anything. That is a good habit to build.

  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. Connect the button

    Write calculate(). Read both boxes and use parseFloat on them. Read the operator. Then use a switch to call the right function. Put the returned answer in #result. Connect calculate() to the button with addEventListener. It now works for normal input. It goes wrong 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. This check belongs here, in the page code. It does not belong 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 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 add and 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 understands return.
  • Then run the three console lines from Why return matters together. add(2, 3) * 10 is the line that makes the idea clear. It gives back an answer you can keep using.
  • The console.log experiment teaches more than any explanation. One word changes, 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, they understand the shape of a function. 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 good arguments both ways. That conversation is software design.