Switch / Case

Use a Switch or Case statement if you are going to have many else if statements or the condition is not inherently boolean in nature (like the value of a string, for example).

Switch Syntax

Same syntax for C++, Java, Javascript, and many other languages.

switch(expression) {
   case value :
      // Code to run
      break; // optional to break out of the switch block
   
   case value :
      // Code to run
      break; // optional to break out of the switch block
   
   /** You can have any number of case statements. **/
   
   default : // Optional case to catch any other possibilities
      // Code to run
}

Example 1 - Switch on Number

The following example creates a random number from 1-10 (inclusive) and decides what to do based on that number. The random number is just a way of faking user input or a value from some other function. The example does something specific for numbers 1, 2, 3, 7, and 9 but all the rest fall under the default case. You will need to scroll down in the example or open it in a new window due to the length.

Example 2 - On Text

This example switches on text instead of a number. Same procedure as numbers, just a string instead. You might need to scroll the example or open it in a new window to see it better.

Final Thoughts

The switch statement is not used on boolean values. It is strictly meant for multiple options similar to a menu or list. General rule of thumb - when your code is a bunch of if...else if statements, it might be better suited for a switch statement unless you are using boolean operators (&& and ||).

Last updated