Mark As Completed Discussion

Switch Statements

In JavaScript, a switch statement is used to perform different actions based on different conditions. It provides a concise way to handle multiple possible values of a variable.

When using switch statements, you specify an expression to be evaluated and a series of cases. Each case contains a value or multiple values that are compared to the expression. If there is a match, the corresponding block of code is executed.

Here's an example to illustrate the usage of a switch statement:

JAVASCRIPT
1const day = 'Monday';
2
3switch (day) {
4  case 'Monday':
5    console.log('It is the beginning of the week.');
6    break;
7  case 'Tuesday':
8    console.log('It is the second day of the week.');
9    break;
10  case 'Wednesday':
11    console.log('It is the middle of the week.');
12    break;
13  case 'Thursday':
14  case 'Friday':
15    console.log('It is almost the weekend.');
16    break;
17  default:
18    console.log('It is the weekend.');
19}

In this example, the switch statement is used to determine the day of the week based on the value of the day variable. Depending on the value, a different message is logged to the console.

Switch statements are especially useful when you have a large number of possible conditions to check. Instead of writing multiple if-else statements, you can use a switch statement for a more concise and readable code.

Now it's your turn to practice using switch statements. Feel free to modify the code example above and see how the output changes. You can also try creating your own switch statements to solve different problems!

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment