CodeBlanks Logo Icon CodeBlanks

Add and subtract

Add and test the addition and subtraction functions.

Add and subtract

In the first lesson you defined the add function. Now we will add the subtract function; it follows the same structure.

function subtract(a, b) { return a - b; }. This subtracts b from a and returns it. Parameter names can stay the same; each function has its own scope.

Keeping related functions side by side makes the code easier to read. We will define all four operations this way in the calculator.

Method body and return

A function's body is the code between the curly braces. Here the computation is done and the result is returned with return.

The return statement ends the function and gives the value on the right to the caller. When you write return a - b;, the call subtract(10, 3) returns 7.

You can also write multiple returns; the first match returns. For example, early return is common in zero checks.

Practice Define the subtract function

Define a subtract(a, b) function that returns a - b. The add function is already defined; the console.log calls at the end are ready.

Starter code

index.js
function add(a, b) {
  return a + b;
}

// Define the subtract function here

console.log(add(10, 3));
console.log(subtract(10, 3));

Sample solution

index.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

console.log(add(10, 3));
console.log(subtract(10, 3));

Expected output

13
7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 subtract body

Question
function subtract(a, b) {
  return ____
}
Answer
function subtract(a, b) {
  return a - b;
}

Explanation: subtract does subtraction.

2 What does subtract(10, 3) return?

  • 13
  • 30
  • 3
  • 7 Correct answer

Explanation: subtract returns a - b; 10 - 3 = 7.

3 Match the operators

Term Meaning
+ Addition
- Subtraction
* Multiplication
/ Division

All lessons in Beginner