How to use switch in Javascript

By FoxLearn 12/18/2024 7:05:22 AM   11
In JavaScript, the `switch` statement is used to perform different actions based on various conditions, similar to a series of `if...else` statements.

Here's the basic syntax of a switch statement:

switch (expression) {
  case value1:
    // code to be executed if expression matches value1
    break;
  case value2:
    // code to be executed if expression matches value2
    break;
  // add more cases if necessary
  default:
    // code to be executed if none of the above cases match
    break;
}

The expression in a switch statement is evaluated once and compared with the values in the case statements. If a match is found, the corresponding code block is executed. The break statement is used to stop the execution of the switch statement; without it, the execution continues to the next case.

Here's an example to demonstrate the usage of switch:

let fruit = "Apple";

switch (fruit) {
  case "Apple":
    console.log("It's an apple");
    break;
  case "Banana":
    console.log("It's a banana");
    break;
  case "Orange":
    console.log("It's an orange");
    break;
  default:
    console.log("It's some other fruit");
    break;
}

The output of this code will be "It's an apple" because the value of fruit matches the first case.