In JavaScript, a switch statement is a control flow statement that allows you to execute different code blocks based on the value of an expression. A switch statement tests the value of an expression against multiple cases. It is an alternative to using multiple if-else statements.
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
case value3:
// Code to be executed if expression matches value3
break;
default:
// Code to be executed if expression doesn't match any of the cases
break;
}
In this example, the variable grade represents the grade of a student. The switch statement checks the value of grade and assigns a corresponding message to the message variable.
If grade is set to "B", the output will be "Good job!".
let grade = "B"; let message; switch (grade) { case "A": message = "Excellent job!"; break; case "B": message = "Good job!"; break; case "C": message = "Fair job!"; break; case "D": message = "Needs improvement."; break; case "F": message = "Failed."; break; default: message = "Invalid grade."; } console.log(message);
Switch statement with dynamic user input
var fruit = prompt("Enter a fruit:"); switch (fruit.toLowerCase()) { case "apple": console.log("The fruit is an apple"); break; case "banana": console.log("The fruit is a banana"); break; case "orange": console.log("The fruit is an orange"); break; default: console.log("Unknown fruit"); break; }
Switch statement with a dynamic expression
function getVehicleType(vehicle) { switch (true) { case vehicle instanceof Car: return "Car"; case vehicle instanceof Motorcycle: return "Motorcycle"; case vehicle instanceof Bicycle: return "Bicycle"; default: return "Unknown"; } } function Car() {} function Motorcycle() {} function Bicycle() {} var vehicle1 = new Car(); var vehicle2 = new Motorcycle(); var vehicle3 = new Bicycle(); console.log(getVehicleType(vehicle1)); // Output: Car console.log(getVehicleType(vehicle2)); // Output: Motorcycle console.log(getVehicleType(vehicle3)); // Output: Bicycle console.log(getVehicleType("boat")); // Output: Unknown