In JavaScript, the equivalent of a “case statement” in other languages like C++ or Java is the switch statement. The switch statement evaluates an expression, then executes statements associated with matching cases. Here’s the syntax of a switch statement:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// code block
}
- The
switchexpression is evaluated once. - The value of the expression is compared with the values of each
caseclause. - If a match is found, the associated block of code is executed.
- If no match is found, the
defaultblock (if present) is executed. - The
breakstatement terminates theswitchstatement. If omitted, execution continues with the next case.
Example
let fruit = "banana";
switch (fruit) {
case "apple":
console.log("Apple is red.");
break;
case "banana":
console.log("Banana is yellow.");
break;
case "orange":
console.log("Orange is orange.");
break;
default:
console.log("I don't know the color of this fruit.");
}
In this example:
- Since
fruitis"banana", the case"banana"matches. - The code block associated with the
"banana"case is executed, printing"Banana is yellow.". - Because there’s a
breakstatement after the"banana"case, theswitchstatement terminates after executing the matching case.
If fruit were “apple”, the output would be “Apple is red.”. If fruit were “grape”, the output would be “I don’t know the color of this fruit.” because there’s no matching case and the default block is executed.