Switch statements are similar to if statements. They allow you to check if a certain condition is true and then execute a certain block of code accordingly. Let’s take a look at how to create switch statements.
Creating Switch Statements
Clear your script and add this bit of code.
var num = 5;
We have a variable named num and it’s value is 5. We then use the switch keyword to start our switch statement. The switch statement searches for a match instead of comparing 2 values. The value passed into the parenthesis is the value that you want to match.
Update your switch statement to this.
alert( 'Match with case 1' );
alert( 'Match with case 2' );
alert( 'No matches found!' );
A couple of things are going on here. First, we use the case keyword to create all the possible values that can match the value in the switch statement. After your case keyword, is the value that you want to match with the switch”s value. After that you insert a colon. Any code after this is then executed. For formatting reasons, we indent all code that will be executed for readability.
You can enter as many lines of code as you want. After you run everything you want to run, then you break that case. The break keyword is used to stop the switch statement from continuing to search for a match. Unlike if-else statements, switch statements goes all the way through. So, you could end up executing more than one case. So, by using break, you’re stopping this from happening. Remember, this will only run if a case is matched. You can create as many cases as you want.
Switch vs If Statements
You can use either of these to perform checks. I personally don’t use switch statements, but there are developers that do. Knowing both of these will help you in the long run. You can use switch statements and you’ll be fine. Same goes for if statements. For this series, we’ll be using if statements.