JavaScript Switch
The JavaScript `switch` statement is used to execute one code block from
multiple options. It is similar to the `else if` statement we learned earlier,
but more convenient because it can be used with numbers, characters, and more.
The syntax of the JavaScript `switch` statement is shown below.
Statment:
switch (expression) {
case value1:
// code block 1
break;
case value2:
// code block 2
break;
...
case valueN:
// code block N
break;
default:
// default code block
}
Example 1
Let's look at a simple example of a `switch` statement in JavaScript.
<Script>
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
</Script>
Output
"Tuesday"
Example 2
Let's explore how the `switch` statement behaves in JavaScript.
<Script>
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Another day");
}
</Script>
Output:
Tuesday
Wednesday