Use of Switch Case in JavaScript with example

The switch statement executes a block of code depending on different cases.

The switch statement us a part of Javascript's "Conditional" statements, which are used to perform different actions bases on different conditions. Use the switch to select one of many blocks of code to be executed.  This is the perfect solution for long, nested if/else statements.

The switch statement evaluates an expression. The values of the expression are then compared with the values of each case in the structure. If there is a match, the associated block of code is executed.

The switch statement is often used together with a break or a default keyboard or both. 

The break keyboard breaks out of the switch block. This will stop the execution of more execution code and/or case testing inside the block. If the break is omitted, the next code block in the switch statement is executed. 

The default keyword specifies some code to run if there is no case match. There can only be one default keyword in a switch. Although this is optional, it is recommended to use it as it takes care of unexpected cases. 




Syntax

switch (expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
    default code block
}

Example

var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
        break;
    default:
        day = "Unknown Day";
}

Views

Post a Comment

0 Comments