Switch is a control structure in the JavaScript programming language that allows you to test a variable or an expression against multiple different values and perform corresponding actions.
The syntax of switch consists of the following parts:
switch (biến) {
case giá_trị_1:
// Hành động khi biến có giá trị là giá_trị_1
break;
case giá_trị_2:
// Hành động khi biến có giá trị là giá_trị_2
break;
...
default:
// Hành động khi không có trường hợp nào khớp với giá trị của biến
}
Where:
Here is an example of how to use switch in JavaScript:
let day = "Monday";
let message;
switch (day) {
case "Monday":
message = "Today is Monday.";
break;
case "Tuesday":
message = "Today is Tuesday.";
break;
case "Wednesday":
message = "Today is Wednesday.";
break;
case "Thursday":
message = "Today is Thursday.";
break;
case "Friday":
message = "Today is Friday.";
break;
default:
message = "Today is a weekend day.";
}
console.log(message);
The output will be "Today is Monday." because the variable day has a value of "Monday".
You can also use numbers or expressions in the cases, for example:
let number = 5;
let result;
switch (true) {
case number > 0 && number < 10:
result = "Number is between 0 and 10";
break;
case number > 10 && number < 20:
result = "Number is between 10 and 20";
break;
default:
result = "Number is not in the specified range";
}
console.log(result);
In this example, the output will be "Number is between 0 and 10" because the variable number has a value of 5 and is within the range from 0 to 10.