Cú pháp
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
...
default:
// statements
}
Ví dụ
<script>
var grade = 'A';
document.write("Vao switch<br>");
switch (grade) {
case 'A': document.write("Gioi<br>"); break;
case 'B': document.write("Kha<br>"); break;
case 'C': document.write("Trung binh<br>"); break;
case 'D': document.write("Yeu<br>"); break;
case 'F': document.write("Truot<br>"); break;
default: document.write("Diem khong hop le<br>");
}
document.write("Thoat switch");
</script>
Đặc điểm quan trọng
- So sánh dùng strict equality (===).
breakbắt buộc để ngăn fall-through (trừ khi cố ý).defaultchạy khi không case nào khớp (không bắt buộc).- Có thể gom case:
case 'A': case 'a': ....
Fall-through có chủ đích
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3: case 4: case 5:
season = "Spring";
break;
// ...
}
Switch vs if-else
- Switch: so sánh một giá trị với nhiều hằng số – nhanh, đọc dễ.
- If-else: điều kiện phức tạp, range, biểu thức boolean.
ES2022: switch expression (chưa chuẩn, stage 3)
Tương lai có thể dùng như biểu thức trả về giá trị.