# Switch case calculator in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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

## 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) {
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

The output in the console: −

19