0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Create Simple Calculator

You can create a simple calculator in JavaScript by defining a function like 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

Inputcalculator(5, 3, '+')
Output8
Inputcalculator(10, 2, '*')
Output20
Inputcalculator(7, 0, '/')
OutputInfinity
🧠

How to Think About It

To build a simple calculator, think of it as a tool that takes two numbers and an operation symbol like +, -, *, or /. You check which operation the user wants, then perform that operation on the two numbers and give back the answer.
📐

Algorithm

1
Get the first number input.
2
Get the second number input.
3
Get the operator input (+, -, *, /).
4
Check which operator was given.
5
Perform the corresponding arithmetic operation.
6
Return or display the result.
💻

Code

javascript
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
Output
8 20 Infinity
🔍

Dry Run

Let's trace calculator(5, 3, '+') through the code

1

Receive inputs

num1 = 5, num2 = 3, operator = '+'

2

Check operator

operator is '+' so perform addition

3

Calculate result

5 + 3 = 8

4

Return result

Return 8

StepOperationResult
1Inputs receivednum1=5, num2=3, operator='+'
2Check operatoroperator is '+'
3Perform addition5 + 3 = 8
4Return result8
💡

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

Using switch statement
javascript
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
Switch makes the code cleaner and easier to read when checking multiple cases.
Using an object map for operations
javascript
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
Using an object map allows easy extension and cleaner code without many if/else or switch.

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.

ApproachTimeSpaceBest For
If/ElseO(1)O(1)Simple and direct checks
Switch StatementO(1)O(1)Cleaner multiple case handling
Object MapO(1)O(1)Easy to extend and maintain
💡
Always check for division by zero to avoid unexpected results like Infinity.
⚠️
Beginners often forget to handle invalid operators, causing errors or wrong outputs.