return trong switch chỉ hợp lệ nếu switch nằm bên trong hàm. Khi return thực thi, hàm kết thúc ngay, code sau switch không chạy.
Ví dụ
Hàm returnDay(val) trả về tên thứ bằng switch có return:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Return trong switch</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: green; }
</style>
</head>
<body>
<h1>Return trong switch statement JavaScript</h1>
Nhập ngày 1-7: <input type="text" class="day" />
<button class="Btn">KIỂM TRA</button>
<div class="result"></div>
<h3>Nhập số 1-7 và nhấn KIỂM TRA</h3>
<script>
const dayInput = document.querySelector(".day");
const resEle = document.querySelector(".result");
function returnDay(val) {
switch (val) {
case 1: return "Thứ Hai";
case 2: return "Thứ Ba";
case 3: return "Thứ Tư";
case 4: return "Thứ Năm";
case 5: return "Thứ Sáu";
case 6: return "Thứ Bảy";
case 7: return "Chủ Nhật";
default: return "Nhập 1-7";
}
}
document.querySelector(".Btn").addEventListener("click", () => {
resEle.textContent = returnDay(parseInt(dayInput.value));
});
</script>
</body>
</html>
Kết quả
Nhập 1 -> "Thứ Hai", 7 -> "Chủ Nhật", khác -> "Nhập 1-7".
Lưu ý: Không dùng break sau return (unreachable). Nên dùng object/map cho mapping đơn giản: const days = {1:'Thứ Hai',...}.