They will all fall back to this same message variable. One neat thing we can also do with a case statement is that if we wanted this message to also display for a result matching not only three, but also one and two, we can define multiple case statements to match it with. For this match, we will set message equal to there are a few posts. Let's set up our case three to match our logic for only matching three posts. For any other condition matches, we will just repeat this process. Since we don't want the logic in this block to continue, we will add a break statement. Let's create a new message variable and we will set it equal to there are no posts. Now everything after this colon is considered a separate logic block, and all code continues to execute until it encounters a break keyword. For example, if we wanted to target zero post, we will write out case zero. Since this will be an integer, the matching result will be a number. Next comes a case keyword followed by the result we wish to match to this condition of num posts. The following format is where things start to differ. Then we will have an open and close bracket just like if-statements. Just like an if-statement, we will supply a condition within parentheses which will just be num posts. Let's go ahead and create a switch statement under this num post display variable. With a switch, you supply a condition and then define any number of cases the condition may match. Since we want to add some additional functionality to the display of this message, in this situation it's better to use a switch statement. If-statements are OK for these situations, but they can also lead to some repeated code throughout your logic. Ternaries are only really good for simple Booleans like this or that logic, but not this, then, and then something else logic. What if we wanted to do something a bit more complex. Instructor: Right now, we are using a ternary to check if we have post and displaying an appropriate message.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |