DEV Community

Max
Max

Posted on

Conditional Statements in JavaScript: Switch

In JavaScript, the switch statement is another way to achieve the conditional statements instead of if else. While doing multi level condition check this one is really helpful.

The Switch Statement

The switch statement evaluates an expression and compares it with a series of cases. If there is a match, the code inside that case is executed. The switch statement is often used as an alternative to the if-else statement when multiple conditions need to be evaluated.

break keyword is used in each case to break the switch statement once the case condition is true, if break is not used then it will check other case condition statements.

default keyword is used at the end of switch, this block will be executed if the above case are not true.

syntax:

switch (expression) {
  case value1:
    // code to be executed when expression matches value1
    break;
  case value2:
    // code to be executed when expression matches value2
    break;
  default:
    // code to be executed when none of the cases match expression
}
Enter fullscreen mode Exit fullscreen mode

Here, expression is the expression to be evaluated, and value1, value2, etc., are the cases to compare with the expression. If the expression matches value1, the code inside that case will be executed. The break keyword is used to exit the switch statement. If none of the cases match the expression, the code inside the default case will be executed.

Example:

let number = 2;

switch (dayOfWeek) {
  case 1:
    console.log("ONE");
    break;
  case 2:
    console.log("TWO");
    break;
  case 3:
    console.log("THREE");
    break;
  case 4:
    console.log("FOUR");
    break;
  case 5:
    console.log("FIVE");
    break;
  default:
    console.log("Invalid Number");
}
Enter fullscreen mode Exit fullscreen mode

In this example, since number is 2, the message "TWO" will be printed to the console.

Top comments (0)