The JavaScript switch statement is a control-flow mechanism that evaluates an expression and executes code blocks based on a strict matching case. It is cleaner and more organized than using a long chain of if...else if statements when checking a single value against multiple options.
Basic Syntax
A standard switch statement uses the switch, case, break, and default keywords:
switch (expression) {
case value1:
// Code runs if expression === value1
break;
case value2:
// Code runs if expression === value2
break;
default:
// Code runs if no cases match
}
How 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: We can stop further execution within the switch block using the Break keyword.
Default: Runs if no cases match. Itβs optional but provides a fallback option.
Core Components
Strict Comparison: JavaScript compares the expression to the case values using strict equality (===). No type conversion happens. A string "5" will not match the number 5.
The break Keyword: This stops the execution inside the block. If you omit break, execution will "fall through" into the next case regardless of whether it matches.
The default Keyword: This acts as a fallback if no matching cases are found. It functions exactly like the final else statement in an if/else block.
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
No more statements in the switch block will be executed.
It is not necessary to break the last case. The switch ends (breaks) there anyway.
*The break keyword is crucial for preventing a "fall-through."
*
*Without break, the code will continue to execute the next case blocks (and the default block if present) even if their values do not match the expression.
*
The default Keyword
The default keyword specifies a block of code to run if there is no case match.
The default keyword is optional.
Example Code
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Invalid Day");
}
Output
Wednesday
Explanation
switch(day) checks the value of day.
If day is 1, it executes case 1.
If day is 2, it executes case 2.
If day is 3, it executes case 3.
break stops the execution from continuing to the next case.
If no case matches, the default block runs.
The expression is compared with each case value using strict equality (===).
References
https://www.geeksforgeeks.org/javascript/switch-case-in-javascript/
https://www.programiz.com/javascript/switch-statement

Top comments (0)