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.

Javascript
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 of grade.
  • Since grade matches 'A', the code block following case 'A': is executed, setting result to "Grade is excellent".
  • The break statement terminates the switch 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

Similar Reads

Switch Statement Syntax

switch (expression) { case value1: // code block 1; break; case value2: // code block 2; break; ... default: // default code block;}...

How Switch Statement Works

Evaluation: The expression inside the switch the statement is evaluated once.Comparison: The value of the expression is compared with each case label (using strict equality ===).Execution: If a match is found, the corresponding code block following the matching case the label is executed. If no match is found, the execution jumps to the default case (if present) or continues with the next statement after the switch block.Break Statement: After executing a code block, the break statement terminates the switch statement, preventing execution from falling through to subsequent cases. If break is omitted, execution will continue to the next case (known as “fall-through”).Default Case: The default case is optional. If no match is found, the code block under default is executed....

Flowchart of Switch Statement

...

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:...