JavaScript Switch Case

please click here for more wordpress cource

JavaScript Switch Case is a control structure used to execute different code blocks based on the value of a given expression. The expression is evaluated and then compared with the cases defined within the switch statement.

Here is the basic syntax of the JavaScript Switch Case statement:

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

Here, the expression is evaluated and compared with the value1, value2, and so on until a match is found. If a match is found, the code block associated with that case is executed. If no match is found, the code block associated with the default case is executed.

The break statement is used to exit the switch block once a match is found. If the break statement is not included, the code will continue to execute the next case, regardless of whether it matches the expression.

Here is an example of using the JavaScript Switch Case statement:

let day = "Monday";

switch(day) {
  case "Monday":
    console.log("Today is Monday");
    break;
  case "Tuesday":
    console.log("Today is Tuesday");
    break;
  case "Wednesday":
    console.log("Today is Wednesday");
    break;
  default:
    console.log("Today is not a weekday");
}

In this example, the day variable is evaluated in the switch statement, and the code block associated with the “Monday” case is executed because the value of day matches “Monday”. The break statement is included to exit the switch block once a match is found, and no other cases are evaluated.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *