Skip to content

How to call a function in switch case in JavaScript | Example code

  • by

It’s very easy to call a function in a switch case in JavaScript. You need to Custom the function or inbuilt function name inside the case block for it.

switch (expression) {
        case expression:

            function();
            break;
        default:

    }

Call a function in switch case in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script type="text/javascript">
    var text;
    var fruits = "Apple"

    switch(fruits) {
      case "Banana":
      hello("Banana is good!");
      break;

      case "Orange":
      hello("I am not a love of orange.");
      break;

      case "Apple":
      hello("Apple is good for Health.");
      break;

      default:
      hello("Fruit...not found");
    } 
    
    function hello(msg){
      alert(msg);
    }
  </script>

</body>
</html>

Output:

How to call a function in switch case in JavaScript

Just wrap the operations in functions so they are reusable

switch (something) {
case 1:
    operation1();
    break;
case 2:
    operation2();
    break;
case 3:
    operation3()
    operation1(); //call operation 1
    break;
default:
    defaultOperation();
    break;
}

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. Required fields are marked *

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