Switch case in JavaScript

Switch case

The switch case is an alternative of if…else statement which does almost the same thing. The switch case statement tests a variable against a series of values until it finds its match. When the match found, the block of statements will get executed. Its syntax is given below.

var x;
switch(x)
{
case:value1;
//Block of code to execute;
break;
case:value2;
//Block of code to execute;
break;
.....
.....
default:
//Block of code to execute;
}

Let us write a code to get the present day.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Program to get day</title>
</head>
<body>
    <script>
        var day = new Date();
    switch(day.getDay()) {
        case 0:
            alert("Today is Sunday.");
            break;
        case 1:
            alert("Today is Monday.");
            break;
        case 2:
            alert("Today is Tuesday.");
            break;
        case 3:
            alert("Today is Wednesday.");
            break;
        case 4:
            alert("Today is Thursday.");
            break;
        case 5:
            alert("Today is Friday.");
            break;
        case 6:
            alert("Today is Saturday.");
            break;   
        default:
            alert("No information available for that day.");
            break;
    }
    </script>
</body>
</html>

The above program will give you the present day of the week.

The switch…case statement differs from the if…else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once JavaScript finds a case clause that evaluates to true, it’s not only executes the code corresponding to that case clause, but also executes all the subsequent case clauses till the end of the switch block automatically.

To prevent this, you must include a break statement after each case (as you can see in the above example). The break statement tells the JavaScript interpreter to break out of the switch…case statement block once it executes the code associated with the first true case.

The break statement is however not required for the case or default clause, when it appears at last in a switch statement. Although, it a good programming practice to terminate the last case, or default clause in a switch statement with a break. It prevents a possible programming error later if another case statement is added to the switch statement.

The default clause is optional, which specify the actions to be performed if no case matches the switch expression. The default clause does not have to be the last clause to appear in a switch statement. Here’s an example, where default is not the last clause.

Leave a Reply