Switch
Learn how to select one block of code from multiple possible options using the JavaScript switch statement.
What is switch?
The switch statement evaluates an expression and compares its value with different case values.
When a matching case is found, its code executes. The break statement normally stops execution from continuing into the next case.
A switch statement helps a program choose from multiple options.
Main Parts of switch
switch
Contains the expression whose value needs to be checked.
case
Defines a value that can match the switch expression.
default
Runs when none of the case values match.
Basic Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
How switch Works
Example 1: Days of the Week
In this example, the switch statement checks a number and prints the corresponding day.
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid Day");
}
Output
Example 2: Course Selection
A switch statement can also be used to select an action based on a course code.
const courseCode = "JS";
switch (courseCode) {
case "JAVA":
console.log("Java Full Stack");
break;
case "DOTNET":
console.log(".NET Full Stack");
break;
case "JS":
console.log("JavaScript Full Stack");
break;
default:
console.log("Course Not Found");
}
Output
Important Note
Why use break?
The break statement stops the switch after the matching case has executed.
Without break, JavaScript can continue executing statements in subsequent cases.
Summary
The switch statement is useful when one expression needs to be compared with multiple possible values. A case defines a possible match, break stops further case execution, and default handles the situation when no case matches.