Lesson Description
The "Switch Statements" Lesson is part of the full, Getting Started with JavaScript, v3 course featured in this preview video. Here's what you'd learn in this lesson:
Kyle explains the concept and implementation of switch statements in JavaScript as an alternative to complex if-else conditions. He demonstrates how to structure a switch statement, handle cases, use the break keyword, and provides examples comparing switch statements to if-else statements. Kyle emphasizes the importance of including break statements to control the flow of execution within switch cases and highlights potential issues with variable scoping in switch statements.
Transcript from the "Switch Statements" Lesson
[00:00:00]
>> WebDevSimplified: Like in JavaScript, where there's lots of different ways to do the same thing, we have switch statements, which is another way to conditionally render different logic, and it's essentially a replacement for really big, complicated if else if conditions. So here is going to be an example of a basic switch statement, but I want to just go ahead and actually write this out from scratch. So what we can do to create a switch statement is we can use the switch keyword followed by inside parentheses, the variable we want to check against a bunch of different values.
[00:00:25]
So let's come in here and we can just say name and we'll set that equal to Kyle. So I want to check the name variable against a bunch of different values to see what it's equal to. So we put in whatever that variable name is, and we'll just call this my name actually. So we'll say my name, and we'll paste that down into there. So that's what's going to go inside the parentheses. You then follow that up with curly braces just like this, and inside these curly braces we need to find individual cases for what we're going to be doing.
[00:00:52]
So I can come in here with a case and the case defines what I expect that value to equal. So if I want to check, see if the name is equal to Kyle, I can say case followed by the value of Kyle, and then I put a colon directly after that. That is essentially saying I want to check if the thing I passed inside my switch statement is exactly equal to the value of Kyle using that triple equal syntax. If it is equal to that, I want to run some code inside of here so I can say console.log.
[00:01:20]
My name is Kyle. There we go. So it'll run this particular piece of code. Now, the important thing you need to understand about switch statements is at the very end of every single switch case that you have, you need to use the break keyword to essentially say you're done running the code for that case. If you forget to add this, there's going to be lots of different bugs that you're going to run into which we'll talk about in the section about common mistakes you may make.
[00:01:41]
Next, if you want to check against other names, you just use the exact same case keyword. Let's say Sally is the case we want to check for. We put a colon directly afterwards, and now inside of here we can write all of our code, so we can say console.log. I am Sally. There we go. And again, don't forget to put the break at the end of where your code is going to be. Once you're done with all the different things that you want, you can also put in a default case.
[00:02:03]
Think about this as the else for an if, and inside of switches, it's called default. So default just uses the word default, followed by a colon, and this is like the fallback if it's not equal to anything, and we can just say console.log. I don't know my name. There we go. And the default case does not need a break statement at the end of it. So this is the overall anatomy of a switch statement. And if we actually run this, you can see it prints out my name is Kyle.
[00:02:28]
If we change our name to Sally, you can see it prints out I am Sally. If we change our name to like John, you can see it prints out I don't know my name. So this works just like an if else if else statement, but it's a little bit more condensed and more narrow in focus. Essentially, the purpose of a switch statement is when you want to check one variable against a lot of different values. That's going to be a great case for a switch statement.
[00:02:51]
Otherwise, if and else is going to be good for pretty much any other thing you're going to run into. Now moving on a little bit further, this is kind of comparing the differences between these two, so we can see here's a switch statement for comparing a favorite animal, and we're checking these different cases of cat, dog, and shark. And this is what the exact same thing would look like in an if-else scenario.
[00:03:11]
So you can see we take that variable name favorite animal equal equal equals, whatever that value is cat. Same thing here, copy that down for dog, same thing here for shark, and then finally an else condition at the end. So essentially they do the exact same thing. It's just two ways to do the same thing. One is better than the other for certain scenarios. So like I said, when do you want to use a switch statement?
[00:03:30]
If you're checking one value and comparing it against multiple values, that's a great case for a switch statement. If you have lots of different conditions you need to check, a switch statement is again going to be a great choice. And if your conditions all use strict equality, because by default a switch statement uses that strict equality, then you're going to want to use a switch statement. Any time you need something more complex or you're comparing different variables, not just one single variable, or you only have like one or two checks, then an if statement is going to be a better option for you.
[00:03:58]
Now I mentioned that you need to include this break keyword after every single one of your switch statements, so I want to show you why that is. Let's say that I removed the break keyword here from Kyle. I have it in the right place for Sally, but I forgot to put it in for Kyle. And now let's say that my name is going to be Kyle. You'll notice something interesting in the output that we have over here.
[00:04:16]
It's printing not only my name is Kyle, but it's also printing I am Sally. And that's because by default the way switch statements work is it looks at each case individually from top to bottom. It first looks at case Kyle and it says, is my name Kyle? And our case the name is Kyle. So what happens is it runs the code in your file until it reaches a break keyword. So it runs the code console.log, my name is Kyle.
[00:04:37]
It runs the code console.log I am Sally, and then it sees this break keyword which tells the code, OK, start running after my switch statement is over. So if you forget to put in a break statement, that means your different cases are going to run together into the same set of code. So now it's actually running multiple pieces of code. While if I have the break in there, you'll notice it's only running one piece of code because it matches Kyle, runs this code, hits the break, and then immediately exits out.
[00:05:00]
Now this may seem confusing, like why would you ever want this break statement, but there are cases where you would want to have multiple cases lead into the same piece of code. Here's a perfect example. I have a switch statement that's checking the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday should all log out that we're in a work day, while Saturday and Sunday are the weekend, so it's going to run out weekend.
[00:05:19]
So here you can see all my cases are bleeding together. It doesn't matter which one of these is matched if it matches Monday or Tuesday or Wednesday or Thursday. Any of these that match are all going to run this one line of code afterwards. So this allows you to check to see if one variable is equal to multiple different values and do the exact same thing for all of them. That's the whole reason why they make you put that break keyword in there to make sure you tell it when you're done checking for these specific values.
[00:05:43]
Same thing here, we match the case of Saturday, so it skips down and runs code such as logging out weekend until it gets to that break statement in particular. And that's why we don't need a break statement for our default case, because it's already the last line of our switch statement, so we don't need to tell it that we're done with our switch statement. Now an interesting thing about switch statements as well, make this a little bit larger so it's easier to see, you'll notice that we don't have any of those curly brackets inside of our cases.
[00:06:08]
You can see here we just indented our code with no curly brackets at all. That's something that's a little bit interesting with switches, but it can lead to particular problems in our code, and that's because we know that scope is only created when we have a curly brace. So here our switch, all of our different cases share the exact same scope. So if I create a variable a set it equal to one here and I create a variable a and I set it the value two here, I'm actually going to get an error because these two variables are in the exact same scope.
[00:06:37]
So I'm redefining the same variable. This is something that I run into as problems all the time. So I'd recommend when you're using complicated switch statements that have lots of code, you can just add in your own curly braces, which I usually do right here at the top, and that allows you to come into here, and that allows you to come down here, put all your code directly inside of there, and I can do the same exact thing here.
[00:07:01]
There we go. Give that a quick save, and now you can see that these variables are inside of their own scope, so they're not conflicting and giving me different errors. So I'd recommend when you're doing case in switch statements, if you have really complicated cases and you're defining variables, wrap it inside these curly braces to make sure each case has its own scope, otherwise they all share the exact same scope.
[00:07:19]
Now again, some common mistakes like I talked about, if you forget to put a break in there, your code will fall through to the next case, which is never usually what you want. And if you're trying to rely on like type coercion automatically happening, switch statements will use this strict equality, so you won't have that strict or that you won't have that type coercion happening automatically for you.
[00:07:36]
Finally, make sure you scope your variables or you will run into weird issues with different errors as you put these different variables together. Now to make sure we understand how these different scoping and switch statements work, I do want to do a quick exercise. Create a switch statement that takes a month in number. It's going to be either one through twelve for January through December, and I want you to return this season.
[00:07:57]
So December, which is twelve, January one, and February two, should return winter, three four five should return spring, six seven eight should return summer, and nine, ten, eleven should return fall. Awesome. So hopefully you had some time to go through this exercise, and if we take a look at the solution for this, we just have a simple function called getSeason, which takes in a month, and our switch statement goes over that particular month.
[00:08:23]
So for the first three cases, twelve, one and two, we want to return winter. And of course I already have some bug in this code, so I'll copy this over and actually fix what this looks like. When you look at the website later, it will be fixed, but I actually no, I don't have an error, sorry. Normally I was thinking I forgot to put the break statement inside of here. We're actually using a return, and since return automatically stops your function from running, it won't run the rest of these different cases.
[00:08:45]
Apologies on that. But you can see here we're returning winter. So it exits out of this function, doesn't run the rest of our cases, and it's going to return up that value of winter. We're going to check three four five for those months to return spring, six seven eight will return summer, and nine, ten, eleven will return fall. Finally, default will just return invalid month. You can see here if I get the season for seven, it is summer, and the season for thirteen, which is a month that doesn't exist, will return invalid month.
[00:09:10]
And again, a little bit different thing about this code is since we're in a function, you can just use the return keyword and that not only returned you from your switch statement but also returned you from the entire function with this specific value. And often when I use switch statements I actually write them very similar to this. I create a separate function with a big switch statement inside of it to return different values based on things where I can use it other places inside my code.
Learn Straight from the Experts Who Shape the Modern Web
- 250+In-depth Courses
- Industry Leading Experts
- 24Learning Paths
- Live Interactive Workshops