Switch / Case
Last updated
Last updated
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).
Same syntax for C++, Java, Javascript, and many other languages.
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.
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.
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 ||).