Common Code Blocks
In some cases, we need to use the same code for multiple switch cases. Let’s see an example of how to do it:
Common Code Blocks Example:
Here, we will same code blocks for two different switch cases.
let grade = 'A'
let result;
switch (grade) {
case 'A':
result = "Grade is excellent"
break;
case 'B':
result = "Grade is good"
break;
case 'C':
result = "Grade is Average "
break;
case 'D':
result = "Grade is Poor"
break;
default:
text = "NO grades achieved";
}
console.log(result)
Output
Grade is excellent
Explanation:
Grade
is assigned the value'A'
.- The
switch
statement evaluates the value ofgrade
. - Since
grade
matches'A'
, the code block followingcase 'A':
is executed, settingresult
to"Grade is excellent"
. - The
break
statement terminates theswitch
statement. Result
is logged to the console, which outputs"Grade is excellent"
.
Note: If multiple switch cases match a value, the first is executed.
JavaScript switch Statement
The JavaScript switch statement evaluates an expression and executes a block of code based on matching cases. It provides an alternative to long if-else chains, improving readability and maintainability, especially when handling multiple conditional branches.
Table of Content
- Switch Statement Syntax
- How Switch Statement Works
- Flowchart of Switch Statement
- Common Code Blocks