6.7 Check multiple statements with switch - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v Voiceover>When checking</v> many compound if-else statements the coding can get a bit laborious and a bit sloppy. So there's a switch statement which is one check against many possible results. To illustrate this, we will once again build a function because we will be calling it repeatedly, and inside that function we'll use the switch command. So let's start off by saying, use.switch gets a function, with one argument X, and here we will use the switch command. It's first argument is what you are testing, so in this case, X. The subsequent arguments to switch are named value pairs. For instance, if X is equal to A, we should return first. If X is equal to B, we should return second. If X is equal to Z, we return last, and if X is equal to C we return third. Now, notice I use this awkward wording on purpose to show that the order of these don't really matter. It does spill over one to the next, but they're each tested independently, and last we can put in a default value, other, in case none of these are true. Let's close off our switch statement, close our function, and run this. We now have this function ready to use. So let's first test it with use.switch. We'll hit tab to auto-complete. Let's put an A. It returns first as desired. We try this again with B, it returns second as we liked. Now let's do it with C. We get third, and, of course, let's test it with something that isn't in there, such as D. If we use it with D, we should get other, because it did not exist. Now there's some quirks to this too. What happens if we use numeric values for this? For instance, use.switch, and let's put in one. It came back as first. We do that again with two, came back as the second one. Let's see three, came back of last. Let's go check that. We will scroll up here. The third argument here, which is Z returns last. So what these numeric values are doing, they find the position in the switch statement, numerically, and returns that value. So using numbers allows you to sort of override the value setting and use the positional setting. Let's test a few more to see what's happening here though. If we do use.switch, put in five, we get other. Other is the default value. So now we've tested the last slot in the switch statement. What happens if we test with a number that goes beyond it, like six? Let's do use.switch, put in six. We got a blank. Nothing was returned, which is kind of odd at first. So let's check if it's null. Is.null, use.switch, a six, true. It is null. So what happens is, if you do the numeric switching and you use a numeric value that's beyond the range of what's available to switch, you're gonna get a null back. So switch statements are a nice, easy way, to write cleaner code, that's more concise to check multiple statements.