Case switch
Case Switch A case switch is a control flow statement used to execute different code blocks based on the value of a variable. It has the following syntax: s...
Case Switch A case switch is a control flow statement used to execute different code blocks based on the value of a variable. It has the following syntax: s...
Case Switch
A case switch is a control flow statement used to execute different code blocks based on the value of a variable. It has the following syntax:
switch (variable_name) {
case value1:
// code block for value1
break;
case value2:
// code block for value2
break;
...
default:
// code block for unknown values
break;
}
How it works:
The variable name is compared to the value1, value2, etc. constants defined earlier.
If a match is found, the code block associated with that value is executed.
The break keyword is used to exit the switch statement after the code block has been executed.
If no match is found, the default block is executed.
Examples:
Here are some examples of using case switch:
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Tuesday":
console.log("Another day!");
break;
default:
console.log("Invalid day!");
}
switch (age) {
case 0:
console.log("Child");
break;
case 18:
console.log("Adult");
break;
default:
console.log("Invalid age");
}
switch (color) {
case "red":
console.log("The color is red!");
break;
case "green":
console.log("The color is green!");
break;
case "blue":
console.log("The color is blue!");
break;
default:
console.log("Invalid color");
}