Câu lệnh switch trong JavaScript **chỉ sử dụng so sánh nghiêm ngặt (===)** - không ép kiểu (type coercion). Nếu không tìm thấy case khớp bằng ===, nó nhảy thẳng vào default.
Ví dụ minh họa vấn đề:
const input = "1"; // String từ input HTML
switch (input) {
case 1: // Number 1
console.log("Số 1");
break;
default:
console.log("Default"); // Chạy vào đây! Vì "1" !== 1
}
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Switch Strict Comparison</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.result { font-size: 20px; font-weight: 500; margin: 10px 0; color: green; }
input { padding: 8px; font-size: 16px; width: 60px; }
button { padding: 8px 16px; cursor: pointer; font-size: 16px; }
</style>
</head>
<body>
<h1>Switch Statement - Strict Comparison (===)</h1>
Nhập ngày 1-7: <input type="text" class="day" id="dayInput" />
<button class="Btn" id="btn">CHECK</button>
<div class="result" id="result"></div>
<h3> Nhấn CHECK - switch dùng === nên input string "1" không khớp case 1 (number) </h3>
<script>
const dayVal = document.querySelector("#dayInput");
const resEle = document.querySelector("#result");
document.querySelector("#btn").addEventListener("click", () => {
const value = dayVal.value; // String!
switch (value) {
case 1: resEle.innerHTML = "Thứ 2"; break;
case 2: resEle.innerHTML = "Thứ 3"; break;
case 3: resEle.innerHTML = "Thứ 4"; break;
case 4: resEle.innerHTML = "Thứ 5"; break;
case 5: resEle.innerHTML = "Thứ 6"; break;
case 6: resEle.innerHTML = "Thứ 7"; break;
case 7: resEle.innerHTML = "Chủ Nhật"; break;
default: resEle.innerHTML = "Nhập giá trị 1-7 (số)"; break;
}
});
</script>
</body>
</html>
Kết quả
Nhập 1 (string) → Hiển thị: "Nhập giá trị 1-7 (số)" vì "1" === 1 là false.
Cách khắc phục:
// Cách 1: Ép kiểu trước switch
switch (parseInt(dayVal.value)) { ... }
switch (Number(dayVal.value)) { ... }
switch (+dayVal.value) { ... } // Unary plus
// Cách 2: Dùng string trong case
switch (dayVal.value) {
case "1": ... break;
case "2": ... break;
// ...
}
// Cách 3: Dùng object/Map thay switch (hiện đại hơn)
const days = {
"1": "Thứ 2", "2": "Thứ 3", "3": "Thứ 4",
"4": "Thứ 5", "5": "Thứ 6", "6": "Thứ 7", "7": "Chủ Nhật"
};
const result = days[dayVal.value] || "Nhập 1-7";
Switch vs If-Else:
| Đặc điểm | switch | if-else |
|---|---|---|
| So sánh | Chỉ === (strict) | Mọi phép so sánh (>, <, <=, !=...) |
| Hiệu năng | Tối ưu (jump table) cho nhiều case | Kiểm tra tuần tự |
| Điều kiện phức tạp | Khó | Dễ dàng |
| Range/interval | Không hỗ trợ | Hỗ trợ |
Switch Expression (ES2025 proposal - Stage 3):
// Tương lai: switch trả về giá trị
const dayName = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};