JavaScript switch Statement
The switch statement evaluates an expression and executes code based on matching cases. Itâs an efficient alternative to multiple if-else statements, improving readability when handling many conditions.
Syntax
switch (expression) {
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
// more cases
default:
// Default code block
}
How the Switch Statement Works
- Evaluation: The expression is evaluated once.
- Comparison: The value of the expression is compared against each case.
- Execution: The block under the matching case runs. If no match, the default block executes (if present).
- Break: Stops further execution within the switch block.
- Default: Runs if no cases match. Itâs optional but provides a fallback option.
Flowchart of Switch Statement:
Now let's understand this with the help of example
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);
Output
Wednesday
In this example
- Day is set to 3.
- The switch statement evaluates day.
- Since day is 3, the case 3 the block is executed, assigning "Wednesday" to dayName.
- The break statement ends the switch statement, preventing execution from continuing into other cases.
Break Keyword
The break keyword is used to terminate the execution of a loop or a switch statement. Once a break is encountered, the program will exit the current block, and no further code within the block will be executed.
Now let's understand this with the help of example
let day = 'Monday';
switch (day) {
case 'Monday':
console.log("Start of the week!");
break;
default:
console.log("Invalid day.");
}
Output
Start of the week!
In this example
- Since day is set to 'Monday', the first case is matched, and "Start of the week!" is logged.
- The break statement then stops further execution, so the default case is not executed.
Default Keyword
The default keyword in a switch statement is used as a fallback option when none of the case labels match the evaluated value. It functions similarly to an else in an if-else chain, ensuring that a default action is executed when no specific conditions are met.
- Fallback Action: If no case matches, the code within the default block is executed, preventing unexpected behavior.
- Optional: The default case is optional and can be omitted if not needed.
- Position: The position of the default case in a switch statement doesn't affect its behavior. It only runs if no previous case matches, regardless of where itâs placed.
Now let's understandnd this with the help of example
let day = 'Holiday';
let message;
switch (day) {
case 'Monday':
message = "Start of the week!";
break;
case 'Tuesday':
message = "Second day of the week.";
break;
default:
message = "Day not recognized."; // Fallback action (if no match)
break;
case 'Friday':
message = "End of the workweek!";
break;
}
console.log(message);
Output
Day not recognized.
In this example
- Switch: It checks day but doesnât match any cases.
- Fallback Action: The default case runs, setting message to "Day not recognized.".
- Position of Default: The default case is placed before 'Friday', but its position doesn't affect its behavior; it only runs when no other case matches.
Common Code Blocks
In some situations, multiple case labels in a switch statement require the same block of code to be executed. Instead of repeating the same code for each case, we can group them together.
Here is the example of common code blocks
let grade = 'B';
let result;
switch (grade) {
case 'A':
case 'B':
case 'C':
result = "Grade is good";
break;
case 'D':
result = "Grade is Poor";
break;
default:
result = "No grades achieved";
}
console.log(result);
Output
Grade is good
In this example
- Grade Assignment: The grade variable is defined as 'B' before the switch statement.
- Grouped Cases: The cases for 'A', 'B', and 'C' share the same message "Grade is good". This allows for cleaner code where we donât need to repeat the same block of code for each case.
- Default Case: The default case handles invalid values (if no cases match), outputting "No grades achieved".
- Output: Since grade = 'B', the output will be "Grade is good".
Difference Between if-Else and Switch Statement
Here is a comparison of if-Else and Switch based on various features:
if-else | Switch |
---|---|
Used for complex conditions and ranges. | Used for exact matches of a single value. |
Slower performance with many conditions. | Faster performance with multiple values to check. |
More flexible for complex scenarios. | Less flexible, limited to specific conditions. |
No fall-through; moves to the next else. | Can have fall-through if break is omitted. |
Uses else for the default condition. | Has a default case to handle unmatched values |