JavaScript
Challenge - Calculator
Combine arithmetic operators, conditionals and functions to write a calculator function.
Calculator challenge
In this challenge you will write a calculator function. It takes two numbers and an operator, then returns the result.
You will pick the operation with a switch. Each case matches one operator: '+', '-', '*', '/'. For unknown operators return null.
This task combines arithmetic operators, conditionals and functions. You can use return instead of break so each case ends on a single line.
Calculator structure
In the calculator, switch (operator) checks the operator. Each case matches one operator string and returns the matching arithmetic result.
For example, in case '+' you write return a + b. You could add an extra if for divide-by-zero safety, but for this task the four basic operations are enough.
Use the default case for unknown operators and return null. That way the caller can easily spot an invalid operator.
Exercise Write the calculate function
Define a function named calculate. It should take a, b and operator parameters. Use switch (operator) to pick one of the four basic operations: '+', '-', '*', '/'. Each case should return the matching result. For unknown operators return null from the default case.
Show example solution
return a + b; etc.). End with default: return null;.
Example solution:
function calculate(a, b, operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return null;
}
}
Test yourself
-
What happens if you forget break at the end of a case in a switch?
switch (op) {
case '+':
return a + b;
// no break
}
- Falls through to the next case
- Throws an error immediately
- Exits the loop
- Halts the program
Show answer
Falls through to the next case — Correct. Without break or return, execution flows into the next case; this is called fall-through.
-
Complete the addition case
function calculate(a, b, operator) {
switch (operator) {
case '+':
return ____;
case '-':
return a - b;
}
}
Show answer
function calculate(a, b, operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
}
}
Next lesson: Challenge - Array operations