 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
 