Create a Calculator function in JavaScript

We have to write a function, say calculator() that takes in one of the four characters (+, - , *, / ) as the first argument and any number of Number literals after that. Our job is to perform the operation specified as the first argument over those numbers and return the result.

If the operation is multiplication or addition, we are required to perform the same operation with every element. But if the operation is subtraction or division, we have to consider the first element as neutral and subtract all other elements from it or divide it by all other elements, based on the operation.

Syntax

calculator(operation, ...numbers)

Parameters

  • operation - A string containing one of four operators: '+', '-', '*', '/'
  • ...numbers - Rest parameters containing the numbers to perform the operation on

How It Works

The function uses the reduce() method to accumulate results. For addition and multiplication, it combines all numbers. For subtraction and division, it starts with the first number and applies the operation with subsequent numbers.

Example

const calculator = (operation, ...numbers) => {
    const legend = '+-*/';
    const ind = legend.indexOf(operation);
    return numbers.reduce((acc, val) => {
        switch(operation){
            case '+': return acc+val;
            case '-': return acc-val;
            case '*': return acc*val;
            case '/': return acc/val;
        };
    });
};

console.log(calculator('+', 12, 45, 21, 12, 6));
console.log(calculator('-', 89, 45, 21, 12, 6));
console.log(calculator('*', 12, 45, 21, 12, 6));
console.log(calculator('/', 189000, 45, 7, 12, 4));
96
5
816480
12.5

Operation Breakdown

Operation Example Input Calculation Result
Addition (+) 12, 45, 21, 12, 6 12 + 45 + 21 + 12 + 6 96
Subtraction (-) 89, 45, 21, 12, 6 89 - 45 - 21 - 12 - 6 5
Multiplication (*) 12, 45, 21, 12, 6 12 × 45 × 21 × 12 × 6 816480
Division (/) 189000, 45, 7, 12, 4 189000 ÷ 45 ÷ 7 ÷ 12 ÷ 4 12.5

Enhanced Version with Error Handling

const calculator = (operation, ...numbers) => {
    // Validate operation
    if (!'+-*/'.includes(operation)) {
        throw new Error('Invalid operation. Use +, -, *, or /');
    }
    
    // Check if numbers are provided
    if (numbers.length === 0) {
        throw new Error('At least one number is required');
    }
    
    return numbers.reduce((acc, val) => {
        switch(operation){
            case '+': return acc + val;
            case '-': return acc - val;
            case '*': return acc * val;
            case '/': 
                if (val === 0) {
                    throw new Error('Division by zero is not allowed');
                }
                return acc / val;
            default: return acc;
        }
    });
};

// Test with valid operations
console.log(calculator('+', 10, 20, 30));
console.log(calculator('*', 2, 3, 4));
60
24

Conclusion

The calculator function demonstrates the power of rest parameters and the reduce method in JavaScript. It provides a flexible way to perform arithmetic operations on multiple numbers with a single function call.

Updated on: 2026-03-15T23:18:59+05:30

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements