Learn
Conditional Statements
The switch keyword
Switch statements are particularly useful when you have a variable or expression that can have different values and you want to execute different code blocks based on those values. Instead of using multiple if-else statements, switch statements offer a concise and more structured approach.
Syntax
The syntax for a switch statement is as follows:
- The
expressionis evaluated once and its value is compared to the values specified in thecaseclauses. - If a match is found, the code block following that case is executed until a
breakstatement is encountered. - If no match is found, the code block following the
defaultcase is executed.
Example
Let's consider a scenario where we want to perform different actions based on a user's role. We'll use a switch statement to handle this:
In this example, if the role is "admin", the first code block will be executed and the message "You have full access privileges." will be logged to the console. Similarly, for "user" and "guest", different code blocks will be executed.
Instructions
Create an empty switch statement based on the value of the day variable.
Use the switch statement to set the value of the message variable.
Handle the following cases inside the switch:
- When
dayis equal to"Monday", setmessageto"It's Monday!". - When
dayis equal to"Tuesday", setmessageto"It's Tuesday!". - When
dayis equal to"Wednesday", setmessageto"It's Wednesday!". - For any other day, set
messageto"It's a different day.".
Make sure to add the break statement on end of every case.
Sign up to start coding
Already have an account?
Sign In
