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 variableday
and assigns it the value"Monday"
.- The
switch (day) { ... }
statement evaluates the value ofday
against multiplecase
values. - Depending on the value of
day
, it executes the correspondingcase
block. - If none of the
case
values match, thedefault
block is executed. - In this example, since
day
is"Monday"
, it matches the firstcase
and assignsmessage
as"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