Flat Preloader Icon

JS Case Statement

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
  case value2:
    // code block
    // 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 the switch statement. If omitted, execution continues with the next case.
					let fruit = "banana";
switch (fruit) {
  case "apple":
    console.log("Apple is red.");
  case "banana":
    console.log("Banana is yellow.");
  case "orange":
    console.log("Orange is orange.");
    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, the switch 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.

Share on: