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
expression
is evaluated once and its value is compared to the values specified in thecase
clauses. - If a match is found, the code block following that case is executed until a
break
statement is encountered. - If no match is found, the code block following the
default
case 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
day
is equal to"Monday"
, setmessage
to"It's Monday!"
. - When
day
is equal to"Tuesday"
, setmessage
to"It's Tuesday!"
. - When
day
is equal to"Wednesday"
, setmessage
to"It's Wednesday!"
. - For any other day, set
message
to"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