JavaScript switch Statement
The switch statement in JavaScript provides an efficient way to execute one block of code from multiple options.
Here's an example of using a switch statement:
var day = "Monday";
var 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 = "It's a weekend day.";
}
console.log(message);
Explanation of the example:
var day = "Monday";: Defines a variabledayand assigns it the value"Monday".- The
switch (day) { ... }statement evaluates the value ofdayagainst multiplecasevalues. - Depending on the value of
day, it executes the correspondingcaseblock. - If none of the
casevalues match, thedefaultblock is executed. - In this example, since
dayis"Monday", it matches the firstcaseand assignsmessageas"Today is Monday.".
All in one Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Switch statement</title>
</head>
<body>
<form action="">
<label for="">Enter a weekday number</label>
<input type="number" id="daynum" />
<br /><br />
<button onclick="weekday();" type="button">Submit</button>
</form>
<script>
function weekday() {
var day = Number(document.getElementById("daynum").value);
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
case 4:
document.write("Thursday");
break;
case 5:
document.write("Friday");
break;
case 6:
document.write("Saturday");
break;
case 7:
document.write("Sunday");
break;
default:
document.write("wrong entry");
}
}
</script>
</body>
</html>
Run Code