DEV Community

Max
Max

Posted on

2 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series