If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Switch statements is something that you can use to execute different actions or cases based on the value of a single JavaScript expression. Consider the simple example where we want to log the price of a fruit. We can easily do that using a switch statement and add its code. The switch statement consists of the switch keyboard followed by an expression that will be used to match against the different case clauses. As an example, if the fruit evaluates to the string apple, we want to log out 1.00. The case clause consists of the case keyword followed by the match value, followed by the colon, followed by the statements that you want to execute.
00:35
For this particular case, we can add as many cases as we need. For example, let's add a case for a banana and an orange, both with their own console log statements that log their individual prices. One very important fact to remember is that we almost always add a break statement at the end of individual case clauses, and this ensures that once that particular case is done, we break out of the switch statement, otherwise it would actually fall through to the next one. As an example, if you forget this particular break in apple after logging out 1.00, it would actually jump into the banana section and log out a 0.50.
01:13
But because we have the breaks in place, apple only logs out 1.0. Banana logs out 0 1 5 0, and there is no fall through between the different case statements. Sometimes you want to execute the same set of code for different values of the conditional switch expression, and for that we can use the fall through pattern. Consider the simple example where we have an H T P status code. That can only be the numbers 200, 300, 400 or 500. For the status code 200, we want to log out the string success and for all of the other codes, 300, 400, 500,
01:46
we want to execute the same code that logs out the string error. Instead of repeating this code block in the individual case statements, we can simply write the case statements and let them fall through by making sure that there is no break between the individual cases. As an example, if the status code is equal to the number 300, it's going to start executing any of the code that follows till it eventually hits the break statement and therefore it will execute this console log error. Adding an optional default clause to your switch statement allows you to handle unexpected values that do not match any of your case clauses.
02:22
Consider the simple example We we are sending the animal to the arc and placing them properly. For example, if the animal is a cat or a dog, we want to put them on the lower deck. If they are a chicken or a pigeon, we want to put them on the upper deck. And finally, for everything else, we want to make them extinct. If you want to capture anything that didn't match any case statement, we can do that with the default clause. And syntax wise, it is very similar to the case statement. It simply consists of the default keyword followed by a colon, followed by the code that we want to execute.
02:54
So now if you run this sent to arc function, a dog would go to the lower deck, a chicken would go to the upper deck and any other value, for example, the string dinosaur will fall through to the default clause and we will log out extinct. Internally, the JavaScript switch statement uses strict equality to compare the conditional expression with the individual case clauses. You can recall that JavaScript strict equality works perfectly fine for primitives like strings or numbers. So Monday is equal to Monday and one is equal to one. However, that is not true for objects.
03:26
So just because two objects are structurally equivalent, unless they are the same reference, they are not going to be strictly equal. With this recap out of the way, considered the simple object person that consists of a name property pointing to the string, John. Now we can be a bit crazy and try to use this object as is in a true statement and say that, Hey, if this person matches an object, name of John a logout, hi John, but this is not going to work. This case is never going to match because the underlying strict equality triple equal is always going to be false.
03:59
The proper way to do this switch statement would be to identify some property that can be used with strict equality and still uniquely identifies the object for our simple case using person do name which is of type string, and using that for the case clauses will work perfectly fine. You can see that hi, John has executed, but hi John will not work is nowhere way to be found in the output. If the code in the switch is within a function and you are going to return from some case, then for obvious reasons you don't need to have a break statement. In that case, consider the example where we have a trust result value,
04:33
which can be zero or one, and we want to return the string version for these values. So if the value is going to be zero, we are going to return the string head. And if the value is one, we return the string tail. Now because the case clauses end in a return statement, there is no need for a break as the code in the switch statement will stop executing just like any other code in the function once we hit the return statement. So tossed result zero will return the string head to result, one will return the string tail and we can verify that from the program output. Let's talk about some of the best practices regarding switch statements.
05:08
And a big thing worth knowing is that case statements don't create a block scope and it's up to you to create them using parentheses. Consider a simple action string that can be say hello or say hi. And then based on the value of action, we want to create a message variable which will be hello or Hi and then log that message out. This code looks perfectly fine, but when we actually try to run it, it'll actually fail. And the reason why is that we are actually declaring the same variable twice within the same scope because there is only one block scope over here and that is dictated by the parentes of the switch statement.
05:44
Now the fix is quite simple. We can actually create a block scope whenever we want by simply using parentheses ourselves so we can wrap the case statement bodies with parentheses, and now they are all Isolated into their own individual block scopes, which means that the message variable created in the first case is completely isolated from the message variable declared in the second case. So now the code will execute without any issues because the action is say hello. The first case block will execute and we see the string hello, log to the console.
06:16
When the evaluated result of the switch statement is a simple expression, it is conventional to replace the switch statement with an object looker pattern to achieve the same result with fewer lines of code. Consider this function office R that takes a particular day string and then based on the value of that string returns of working hours for that day, we have values for all the days Monday to Friday. And then for everything else which are weekends, we return the string closed. So if you pass in the string Thursday, we get 11 to four, and if you pass in the string Sunday we get closed.
06:49
Note that our function body consists of a simple mapping of one string to another along with the potentially default value. A feature of surescript is that we can actually use simple objects to create a mapping from one string to another. So from Monday to Friday we can provide the string values and then we can fetch the desired value from this object by using an index lookup passing in the provided day. Now, if the provided day does not exist within this object, for example, Sunday does not exist, then the Jiao script on time will give us the value undefined, which of course we can now call less to a default value. For example, hey,
07:24
we are defaulting it to the string closed. So if you passing in the string Thursday, it's going to look up the value for the string, and of course it's going to be 11 to four and for everything that is not present, for example, passing in the string Sunday, we get back the default value of closed. So in summary, in the object lookup pattern on the left hand side, we have the case clauses. On the right hand side we have the case results. The conditional switch expression is used as the lookup, and now coalescing is used to provide the default result. The object lookup pattern is a more functional programming inspired expression based version of a switch statement. I hope you enjoyed this tutorial.
08:01
As always, thank you for joining me and I will see you in the next one.