Hello all, hope you are all doing well, today we’re going to have a look at switch statements which are a completely new subject to me. Let’s dig in! And as always, thanks to FreeCodeCamp for the lessons.
Selecting from Many Options with Switch Statements
A switch statement tests a value and can run many case statements, which define various outcomes, each separated by a break.
Remember: case values are tested with strict equality (===).
Note: The break tells JS that the code has come to an end and needs no more execution to take place, and moves JS onto the next case, if any given.
Take a look here at the example given by FreeCodeCamp:
As we can see here, the switch statement opens with a condition called lowercaseLetter, and assigns each case value (each letter of the alphabet) to the console.log as the capital letter equivalent of that value. Note the positioning of each case and break here. We can see how this could be applied for the whole alphabet.
Also notice how all cases take place within the curly brackets of the switch statement.
Adding a Default Option
We can use default statements, which act like else statements at the end of an if/else statement chain. This is a way of setting the “default” option if no other case statement can be applied in the code.
Note: Default statements must be entered last in the chain.
Multiple Identical Options in Switch Statements
In the event of multiple case statements, we can arrange them like so:
Note: The first three case value options have no break between them so the code is executed for all of them together and they all produce the same result.
Remember: When writing these multiple grouped case options, don’t forget to have the break between each group!
Replacing If Else Statement Chains with Switch Statements
We can tidy up an if/else statement chains with switch instead, take a look how that is tidied up, notice the strict equality operator also:
Aaaaand let’s call it there, that brings us to an end of switch statements in the lessons at FreeCodeCamp, thanks for reading and learning with me! I had alot of fun learning about these, especially how simple and easy to read they are.
Til next time!