JavaScript Program to Create Simple Calculator
function calculator(num1, num2, operator) { if (operator === '+') return num1 + num2; else if (operator === '-') return num1 - num2; else if (operator === '*') return num1 * num2; else if (operator === '/') return num1 / num2; else return 'Invalid operator'; } which takes two numbers and an operator to return the calculation result.Examples
How to Think About It
Algorithm
Code
function calculator(num1, num2, operator) { if (operator === '+') return num1 + num2; else if (operator === '-') return num1 - num2; else if (operator === '*') return num1 * num2; else if (operator === '/') return num1 / num2; else return 'Invalid operator'; } console.log(calculator(5, 3, '+')); // 8 console.log(calculator(10, 2, '*')); // 20 console.log(calculator(7, 0, '/')); // Infinity
Dry Run
Let's trace calculator(5, 3, '+') through the code
Receive inputs
num1 = 5, num2 = 3, operator = '+'
Check operator
operator is '+' so perform addition
Calculate result
5 + 3 = 8
Return result
Return 8
| Step | Operation | Result |
|---|---|---|
| 1 | Inputs received | num1=5, num2=3, operator='+' |
| 2 | Check operator | operator is '+' |
| 3 | Perform addition | 5 + 3 = 8 |
| 4 | Return result | 8 |
Why This Works
Step 1: Input handling
The function takes two numbers and an operator as inputs to know what to calculate.
Step 2: Operator check
It uses if and else if to find which arithmetic operation to perform.
Step 3: Perform calculation
Based on the operator, it does addition, subtraction, multiplication, or division using +, -, *, or /.
Step 4: Return result
The function returns the calculated value or an error message if the operator is invalid.
Alternative Approaches
function calculator(num1, num2, operator) { switch(operator) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; default: return 'Invalid operator'; } } console.log(calculator(4, 2, '-')); // 2
const operations = { '+': (a, b) => a + b, '-': (a, b) => a - b, '*': (a, b) => a * b, '/': (a, b) => a / b }; function calculator(num1, num2, operator) { const operation = operations[operator]; return operation ? operation(num1, num2) : 'Invalid operator'; } console.log(calculator(6, 3, '/')); // 2
Complexity: O(1) time, O(1) space
Time Complexity
The calculator performs a fixed number of checks and one arithmetic operation, so it runs in constant time.
Space Complexity
It uses a fixed amount of memory for inputs and no extra data structures, so space is constant.
Which Approach is Fastest?
All approaches run in constant time; using an object map is clean and scalable, while if/else or switch are straightforward.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If/Else | O(1) | O(1) | Simple and direct checks |
| Switch Statement | O(1) | O(1) | Cleaner multiple case handling |
| Object Map | O(1) | O(1) | Easy to extend and maintain |