JavaScript switch Statement: A Complete Tutorial with Examples

The switch statement in JavaScript is a control structure used to execute different code blocks based on the value of an expression.

It is a more readable alternative to multiple if…else statements when dealing with multiple conditions.

Syntax of switch Statement

switch(expression) {
  case value1:
    // Code to execute if expression === value1
    break;
  case value2:
    // Code to execute if expression === value2
    break;
  ...
  default:
    // Code to execute if none of the cases match
}

Explanation

switch(expression): The expression whose value is compared against the cases.
case value: Each case compares its value with the expression.
break: Exits the switch block. If omitted, the next case will be executed regardless of the match.
default: Optional. Executes if none of the case values match the expression.

1. Basic switch Statement Example

Here’s a simple example using the switch statement to match a variable against different fruit names:

let fruit = 'apple';

switch(fruit) {
  case 'apple':
    console.log('Apples are $1 per pound.');
    break;
  case 'banana':
    console.log('Bananas are $0.50 per pound.');
    break;
  case 'cherry':
    console.log('Cherries are $3 per pound.');
    break;
  default:
    console.log('Sorry, we are out of that fruit.');
}

Output: Apples are $1 per pound.

Explanation

The switch statement checks the value of fruit.
When fruit is ‘apple', it matches case ‘apple', executes its code, and exits the switch block due to the break.

2. Using default in a switch Statement

The default case executes if none of the specified cases match the expression. This is similar to the else statement in an if…else block.

let color = 'purple';

switch(color) {
  case 'red':
    console.log('You chose red.');
    break;
  case 'green':
    console.log('You chose green.');
    break;
  case 'blue':
    console.log('You chose blue.');
    break;
  default:
    console.log('Color not recognized.');
}

Output: Color not recognized.

Explanation

Since color is ‘purple' and none of the cases match, the default case executes.

3. Multiple Cases with the Same Code

You can group multiple case labels together to execute the same code block:

let day = 'Saturday';

switch(day) {
  case 'Monday':
  case 'Tuesday':
  case 'Wednesday':
  case 'Thursday':
  case 'Friday':
    console.log('It\'s a weekday.');
    break;
  case 'Saturday':
  case 'Sunday':
    console.log('It\'s the weekend!');
    break;
  default:
    console.log('Not a valid day.');
}

Output: It's the weekend!

Explanation

If day is ‘Saturday' or ‘Sunday', the same code block runs because they are grouped together.

4. Omitting break for Fall-Through

If the break statement is omitted, JavaScript will continue executing the next case statements (known as fall-through). While this is generally not recommended, it can be used in specific scenarios.

let score = 'B';

switch(score) {
  case 'A':
    console.log('Excellent!');
    break;
  case 'B':
  case 'C':
    console.log('Well done!');
    break;
  case 'D':
    console.log('You passed.');
    break;
  case 'F':
    console.log('Try again.');
    break;
  default:
    console.log('Invalid grade.');
}

Output: Well done!

Explanation

When score is ‘B', it falls through to the next line (case ‘C') since they share the same console.log().

5. Using Expressions in switch Statements

The switch statement can also handle complex expressions:

let number = 10;

switch(true) {
  case (number < 0): console.log('Number is negative.'); break; case (number === 0): console.log('Number is zero.'); break; case (number > 0):
    console.log('Number is positive.');
    break;
  default:
    console.log('Not a valid number.');
}

Output: Number is positive.

Explanation

The switch expression here uses true to allow the use of conditions within the case statements.

6. Nesting switch Statements

You can nest switch statements within each other, but this should be done with caution to avoid overly complex code.

let animalType = 'mammal';
let animalName = 'dog';

switch(animalType) {
  case 'mammal':
    switch(animalName) {
      case 'dog':
        console.log('It\'s a dog, a friendly mammal.');
        break;
      case 'cat':
        console.log('It\'s a cat, an independent mammal.');
        break;
      default:
        console.log('Unknown mammal.');
    }
    break;
  case 'bird':
    console.log('It\'s a bird.');
    break;
  default:
    console.log('Unknown animal type.');
}

Output: It's a dog, a friendly mammal.

Explanation

The outer switch checks the type of animal (animalType).
If it's a ‘mammal', it enters an inner switch to check the specific animal name (animalName).

Conclusion

The switch statement is a powerful tool in JavaScript for handling multiple conditions. It is particularly useful when you have a variable that can take on a discrete set of values.

The use of case, break, and default statements allows for flexible and readable code.

Key Points to Remember
Use break to prevent fall-through.
Group multiple case statements to run the same code.
The default case is optional but useful as a fallback.
switch statements can handle complex conditions when used with expressions.

Now that you have a thorough understanding of switch statements, you can apply them to various scenarios in your JavaScript programming!

Related posts

JavaScript if else Statement Tutorial with Examples

JavaScript break Statement: A Complete Tutorial with Examples

JavaScript continue Statement: A Complete Tutorial with Examples