JavaScript Switch Statement

The switch statement in JavaScript is used to perform different actions based on different conditions. It's a cleaner way to handle multiple possible conditions instead of using multiple if...else statements.


Basic Syntax

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

        
    

Example

Here's a simple example of a switch statement that checks the day of the week:

Try yourself
        
            
let day = 'Wednesday';

switch (day) {
    case 'Monday':
        console.log('It\'s Monday!');
        break;
    case 'Tuesday':
        console.log('It\'s Tuesday!');
        break;
    case 'Wednesday':
        console.log('It\'s Wednesday!');
        break;
    default:
        console.log('It\'s some other day.');
}

        
    

Nested Switch Statements

You can also use nested switch statements for more complex logic. Here's an example:

Try yourself
        
            
let meal = 'lunch';
let food = 'sandwich';

switch (meal) {
    case 'breakfast':
        switch (food) {
            case 'cereal':
                console.log('Enjoy your cereal for breakfast.');
                break;
            case 'toast':
                console.log('Enjoy your toast for breakfast.');
                break;
            default:
                console.log('What are you having for breakfast?');
        }
        break;
    case 'lunch':
        switch (food) {
            case 'sandwich':
                console.log('Enjoy your sandwich for lunch.');
                break;
            case 'salad':
                console.log('Enjoy your salad for lunch.');
                break;
            default:
                console.log('What are you having for lunch?');
        }
        break;
    default:
        console.log('What time is your meal?');
}

        
    

Summary

The switch statement is a useful control structure in JavaScript for handling multiple conditions efficiently. It can replace multiple if...else statements when you need to compare a value to multiple possible values.