Calculator using switch case in JavaScript | Complete code

  • by

Simple take input “add”, “divide”, “multiply”, or “subtract” option form use along with 2 numbers then Calculator using switch case in JavaScript.

Calculator using switch case in JavaScript

Simple example code user is prompted to enter an operator (either +, , * or /) and two numbers.

<!DOCTYPE html>
<html>
<body>

  <script>
    
    let result;

    const operator = prompt('Enter operator ( either +, -, * or / ): ');


    const number1 = parseFloat(prompt('Enter first number: '));
    const number2 = parseFloat(prompt('Enter second number: '));

    switch(operator) {
      case '+':
      result = number1 + number2;
      console.log(`${number1} + ${number2} = ${result}`);
      break;

      case '-':
      result = number1 - number2;
      console.log(`${number1} - ${number2} = ${result}`);
      break;

      case '*':
      result = number1 * number2;
      console.log(`${number1} * ${number2} = ${result}`);
      break;

      case '/':
      result = number1 / number2;
      console.log(`${number1} / ${number2} = ${result}`);
      break;

      default:
      console.log('Invalid operator');
      break;
    }
  </script>

</body>
</html
>

Output:

Calculator using switch case in JavaScript

You can simply add a button to call a function like this

<script>
    function Calculatrice(a, b, op) {

      switch (op) {

        case '+':
        return a + b
        break;
        case '-':
        return a - b
        break;
        case '*':
        return a * b
        break;
        case '/':
        return a / b
        break;
        
      }
    }
    console.log(Calculatrice(5, 5, '+'));
    
</script>

Output: 10

Do comment if you have any doubts or suggestions on this JS switch case topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.