
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
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
The output in the console: −
19
- Related Articles
- Java program to generate a calculator using the switch case
- Java Program to Make a Simple Calculator Using switch...case
- Golang Program to make a Simple Calculator using Switch Case
- How to use case-insensitive switch-case in JavaScript?
- What is Switch...case statement in JavaScript?
- C++ Program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case
- Switch case in Arduino
- How to come out of a switch case in JavaScript?
- Switch case statement in C
- Switch Case in Python (Replacement)
- String in Switch Case in Java
- The String in Switch Case in Java
- Explain nested switch case in C language
- Using range in switch case in C/C++
- How to implement switch-case statement in Kotlin?

Advertisements