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
switch
expression is evaluated once. - The value of the expression is compared with the values of each
case
clause. - If a match is found, the associated block of code is executed.
- If no match is found, the
default
block (if present) is executed. - The
break
statement terminates theswitch
statement. 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
fruit
is"banana"
, the case"banana"
matches. - The code block associated with the
"banana"
case is executed, printing"Banana is yellow."
. - Because there’s a
break
statement after the"banana"
case, theswitch
statement 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.