Switch Statements to the Rescue
Day 21- Making 2D Space Shooter Game
Switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.
If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
The expression in the Switch statement denotes a value or a variable that will be compared with the value in the case which if found same runs among all others. Break is used to indicate that it is the end of the case and finally default is when the expression doesn’t match any value in cases.
Here you could have used if else if statement but what if there are 50 similar powerups. So you use Switch statement when you need to compare similar value of same datatype to run some statements. In above script, you are using if statement to compare the int value to check each power-up.
Here you can use switch statement and you can already see the difference. Switch statement make the same logic feels more understandable and is more clear to read. As you add more powerups, you can just add a new case instead of going through a if statement.