JavaScript Switch
Syntax
The syntax for a switch statement in JavaScript is as follows:
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
...
default:
// Code to be executed if expression doesn't match any of the values
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruit Selection Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Assign a value to the constant 'fruit'
const fruit = 'apple';
// Use a switch statement to determine the output based on the value of 'fruit'
switch (fruit) {
case 'banana':
document.getElementById("output").innerHTML = 'I want a banana';
break;
case 'orange':
document.getElementById("output").innerHTML = 'I want an orange';
break;
case 'apple':
document.getElementById("output").innerHTML = 'I want an apple';
break;
default:
document.getElementById("output").innerHTML = 'I don\'t want any fruit';
}
</script>
</body>
</html>
Output
I want an apple