Code Highlights logo

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:

1switch (expression) {
2 case value1:
3 // code block to execute if expression matches value1
4 break;
5 case value2:
6 // code block to execute if expression matches value2
7 break;
8 case value3:
9 // code block to execute if expression matches value3
10 break;
11 // more cases...
12 default:
13 // code block to execute if none of the cases match
14}
  • The expression is evaluated once and its value is compared to the values specified in the case 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:

1let role = "admin";
2
3switch (role) {
4 case "admin":
5 console.log("You have full access privileges.");
6 break;
7 case "user":
8 console.log("You have limited access privileges.");
9 break;
10 case "guest":
11 console.log("You have read-only access.");
12 break;
13 default:
14 console.log("Invalid role.");
15}

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

1.

Create an empty switch statement based on the value of the day variable.

2.

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", set message to "It's Monday!".
  • When day is equal to "Tuesday", set message to "It's Tuesday!".
  • When day is equal to "Wednesday", set message to "It's Wednesday!".
  • For any other day, set message to "It's a different day.".

Sign up to start coding

Already have an account?

Sign In

Course content