JavaScript Switch

The `switch` statement in JavaScript is used to perform different actions based on different conditions. It is an alternative to using multiple `if-else` statements and can be more readable in certain situations.

1. Basic Switch Statement

The basic syntax of a `switch` statement is as follows:


// Basic switch statement
let day = 2;
let dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Invalid day";
}

console.log(dayName); // Output: Tuesday

            

2. Switch with Multiple Cases

You can group multiple cases together to handle the same block of code:


// Switch with multiple cases
let fruit = "apple";
let color;

switch (fruit) {
    case "apple":
    case "cherry":
        color = "red";
        break;
    case "banana":
    case "lemon":
        color = "yellow";
        break;
    default:
        color = "unknown";
}

console.log(color); // Output: red

            

3. Switch with Default Case

The `default` case is optional but recommended. It executes when none of the `case` values match the expression:


// Switch with default case
let number = 4;
let result;

switch (number) {
    case 1:
        result = "One";
        break;
    case 2:
        result = "Two";
        break;
    default:
        result = "Not One or Two";
}

console.log(result); // Output: Not One or Two