Add and subtract
- Node.js course
- Beginner
- Lesson 20/116
- 6 min
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
function add(a, b) {
return a + b;
}
// Define the subtract function here
console.log(add(10, 3));
console.log(subtract(10, 3));Sample solution
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
function subtract(a, b) {
return ____
}
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 |