JavaScript in Plain Language (2015)
PART III: STRENGTHENING THE WARRIOR'S ARSENAL
3.5 More branching techniques
The switch
So far we have learned about the if(), possible else if() and optional else conditional statements, right?
if(true) {
// do this;
} else if(true) {
// do that;
} else {
// do this one instead;
}
You can do any possible outcome by using the above powerful combination of if, elses.
Sometimes however, a different kind of branching makes more sense. I’m talking about the one known as Switch and I just want to make sure it is explained in case you need to use it.
It is called switch because there are several possible outcomes from which JavaScript makes an executable decision. These possible outcomes are all in off state, and JavaScript will turn one on based on a matching Boolean condition, as we you’ll see next.
Here’s the layout diagram:
Fig 16
On line 1 we declare a switch. This switch function method takes a condition from which JavaScript will compare all the outcomes in order to select one of the possible executions.
In our generic example (based on the cases we have), the “condition to match” should be substituted by either a 1, 2, or 3, so it matches one of the cases presented. If any of these cases matches the condition, JavaScript executes the code given by the case. The Boolean true is what unlocks the case.
Example: if the correct case is 3, JavaScript will ask:
“is it 1? Ans: false”,
is it 2? Ans: false”,
is it 3? Ans: true”, run the code,
BREAK and END.
After the execution of a case, JavaScript exits the switch due to the break command that follows. If we don’t include the break command, then JavaScript will search for more possible results and you may have several correct answers instead of just one. And even if there are no other correct answers, JavaScript still reads all the other conditions which could be a time delay if the switch has thousands of possibilities programmed in it. So the break is a very important implementation.
Whenever there are no conditions that match, the optional default takes over as the final and true option and its code is executed. Notice that I did not include a break after default. You could, but it is not necessary because JavaScript exits the switch at this time anyway.
For further reading please visit this post | bit.ly/1r4XRCL on the forum. Let’s practice a bit with switches.