JavaScript Switch

What is Switch Case in JavaScript?

In JavaScript, a switch case is a conditional statement that is used so it can provide a way to execute the statements based on their conditions or different conditions. A switch case statement is used to perform different actions based on the conditions that are present in the program or given by the user. In other words, a switch statement evaluates the condition to match the condition with the series of cases and if the condition is matched then it executes the statement. If the condition is not matched with any case then the default condition will be executed. In JavaScript, a switch case statement is an alternative approach for if else conditions. The JavaScript switch statement is used to execute one code from multiple expressions. But it is convenient that if else if because it can be used with numbers, characters etc.

Key Points on Switch Statement:

Syntax of Switch Statement:

Syntax


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
}

Example of Switch Statement in JavaScript:

This example uses a switch statement to check the day of the week based on a number.

Example


let day = 3;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday");
        break;
    case 4:
        console.log("Thursday");
        break;
    case 5:
        console.log("Friday");
        break;
    case 6:
        console.log("Saturday");
        break;
    case 7:
        console.log("Sunday");
        break;
    default:
        console.log("Invalid day");
    }

Output

Wednesday

Detailed Explanation:

By using switch statements effectively, developers can create cleaner and more readable code when dealing with multiple conditions that are based on fixed values.