🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Switch Statement

JavaScript Switch Statement

JavaScript Switch Statement

The switch statement in JavaScript provides a way to perform different actions based on the value of an expression. It is often used as an alternative to a series of if-else statements when there are multiple possible matches for a given value. The basic syntax of a switch statement looks like this:

let expression = value;

switch (expression) {
  case value1:
    // Code to be executed if expression === value1
    break;

  case value2:
    // Code to be executed if expression === value2
    break;

  // Additional cases...

  default:
    // Code to be executed if none of the cases match
}

Example:

let day = 3;
let dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break;

  case 2:
    dayName = "Tuesday";
    break;

  case 3:
    dayName = "Wednesday";
    break;

  case 4:
    dayName = "Thursday";
    break;

  case 5:
    dayName = "Friday";
    break;

  case 6:
    dayName = "Saturday";
    break;

  case 7:
    dayName = "Sunday";
    break;

  default:
    dayName = "Invalid day";
}

console.log(dayName); // Outputs: "Wednesday"

In this example:

  • The switch statement evaluates the value of the day variable.
  • Each case represents a possible value of day.
  • If a match is found, the corresponding block of code is executed until the break statement is encountered.
  • If no match is found, the code inside the default block is executed.

Note that the break statement is crucial to exit the switch block once a matching case is found. If you omit the break, the execution will "fall through" to the next case, and so on.

Switch statements are particularly useful when you have a value that may have multiple possible matches and you want to avoid a series of if-else statements.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.