switch/case
As we've seen, we can use if
/else
to perform certain actions based on which conditions are true. This is great when you're evaluating multiple conditional statements to determine flow, such as the following:
if (checkThisCondition) { // Do something ... } else if (checkAnotherCondition) { // Do something else ... }
When we're evaluating the different possibilities of a single variable, however, we have a different statement available to us: the switch
statement. This allows us to branch in a similar way to an if
/else
statement, but each branch is based on a different possible value of a single variable that we're switching on.
A good example of where this would be suitable is the menu application we created...