Switch case calculator in JavaScript

Let's say, we are required to write a JavaScript function that takes in a string like these to create a calculator ?

"4 add 6"
"6 divide 7"
"23 modulo 8"

Basically, the idea is that the string will contain two numbers on either sides and a string representing the operation in the middle.

The string in the middle can take one of these five values ?

"add", "divide", "multiply", "modulo", "subtract"

Our job is to return the correct result based on the string

Syntax

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // default code block
}

Example

Let's write the code for this function ?

const problem = "3 add 16";
const calculate = opr => {
    const [num1, operation, num2] = opr.split(" ");
    switch (operation) {
        case "add":
            return +num1 + +num2;
        case "divide":
            return +num1 / +num2;
        case "subtract":
            return +num1 - +num2;
        case "multiply":
            return +num1 * +num2;
        case "modulo":
            return +num1 % +num2;
        default:
            return 0;
    }
}
console.log(calculate(problem));

Output

19

Testing Multiple Operations

Let's test the calculator with different operations to verify it works correctly:

const calculate = opr => {
    const [num1, operation, num2] = opr.split(" ");
    switch (operation) {
        case "add":
            return +num1 + +num2;
        case "divide":
            return +num1 / +num2;
        case "subtract":
            return +num1 - +num2;
        case "multiply":
            return +num1 * +num2;
        case "modulo":
            return +num1 % +num2;
        default:
            return "Invalid operation";
    }
}

// Test different operations
console.log("Addition:", calculate("4 add 6"));
console.log("Division:", calculate("12 divide 3"));
console.log("Subtraction:", calculate("10 subtract 7"));
console.log("Multiplication:", calculate("5 multiply 8"));
console.log("Modulo:", calculate("23 modulo 8"));
console.log("Invalid:", calculate("5 power 2"));
Addition: 10
Division: 4
Subtraction: 3
Multiplication: 40
Modulo: 7
Invalid: Invalid operation

How It Works

The function uses destructuring assignment to extract three parts from the input string: num1, operation, and num2. The unary plus operator + converts string numbers to actual numbers. The switch statement checks the operation string and executes the corresponding mathematical operation.

Conclusion

The switch statement provides a clean way to handle multiple operations in a calculator. This approach is more readable than multiple if-else statements and easily extensible for additional operations.

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

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements