Multiply and divide
- Node.js course
- Beginner
- Lesson 21/116
- 6 min
Add multiplication, division and the divide-by-zero check.
Multiply and divide
Now we will add multiply and divide functions to the calculator. Multiplication is simple with return a * b.
Division has a quirk: division by zero. In JavaScript, 5 / 0 gives Infinity, -5 / 0 gives -Infinity. This is usually unwanted.
So in the divide function, we first check whether the divisor is zero; if so, we return 0. This prevents the unexpected Infinity result.
Zero division check
In the divide(a, b) function, we first check b. If you write if (b === 0) return 0;, the function immediately returns 0 when the divisor is zero.
This is a technique called early return. If the condition holds, the rest of the function does not run; you write more readable code.
If not zero, normal division is done with return a / b;. This way the calculator runs safely.
Practice Define multiply and divide
Define multiply(a, b) and divide(a, b) functions. multiply returns a * b; divide returns 0 if b === 0, otherwise a / b. add and subtract are already defined.
Starter code
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Define multiply and divide functions here
console.log(multiply(6, 7));
console.log(divide(10, 2));Sample solution
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) return 0;
return a / b;
}
console.log(multiply(6, 7));
console.log(divide(10, 2));Expected output
42 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the multiply/divide concepts
| Term | Meaning |
|---|---|
a * b |
Multiplication |
a / b |
Division |
b === 0 |
Zero check |
return 0 |
Error case |
2 What should the body of multiply(a, b) be?
- return a * b; Correct answer
- return a + b;
- return a - b;
- return a / b;
Explanation: multiply does multiplication; returns a * b.
3 Zero check
if (____) return 0;
if (b === 0) return 0;
Explanation: b === 0 checks strict equality.