Skip to content

JavaScript switch case string | Example code

  • by

JavaScript switch case statement executes a block of code depending on different cases. The switch statement evaluates an expression, string, or integer. If there is a match, the associated block of code is executed.

switch(expression) {
  case n:
    code block
    break;
  case n:
    code block
    break;
  default:
    default code block
}

JavaScript switch case string

A simple example code executes a block of code with a switch case string match.

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

    switch(fruits) {
      case "Banana":
      text = "Banana is good!";
      break;
      case "Orange":
      text = "I am not a love of orange.";
      break;
      case "Apple":
      text = "Apple is good for Health.";
      break;
      default:
      text = "Fruit...not found";
    } 
    console.log(text)
  </script>

</body>
</html>

Output:

JavaScript switch case string

Another example

var flower = "tulip";

switch (flower){
    case "rose":
        console.log("Roses are red");
        break;
    case "violet":
        console.log("Violets are blue");
        break;
    case "sunflower":
        console.log("Sunflowers are yellow");
        break;
    default:
        console.log("Please select another flower");
}

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading