![]() Now we can write that as a switch statement. In the conditional statements tutorial, we made a grading app which would take a number score and convert it to a letter grade, with the following requirements. To make this easier to understand, we will use a familiar example. We can do this by setting our expression to true and doing an operation within each case statement. There might be an occasion in which you will need to evaluate a range of values in a switch block, as opposed to a single value as in our example above. In order to make our programs faster and more efficient, we include the break. If we had omitted the break keyword in each statement, none of the other case statements would have evaluated to true, but the program would have continued to check until it reached the end. We also could have, for example, only printed results for Monday to Friday, and the default block could have had the same message for the weekend. We have included a default block at the end to run in case of an error, which in this case should not happen as there are only 7 days of the week. Depending on what day of the week you are testing the code, your output will be different. This code was tested on a Thursday, which corresponds to 4, therefore the console output was Just one more day 'til the weekend!. Output'Just one more day 'til the weekend!' The program will run in order from top to bottom looking for a match, and once one is found, the break command will halt the switch block from continuing to evaluate statements. Using switch, we will send a message to the console each day of the week. 0 stands for Sunday, all the way through 6 which stands for Saturday. In this code block, we will find the current day of the week with the new Date() method, and getDay() to print a number corresponding to the current day. Let’s make a working example of a switch statement following the syntax above.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |