WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Switch Statement


The switch explanation is utilized to perform diverse activities dependent on various conditions.


The JavaScript Switch Statement

Use the change explanation to choose one of numerous squares of code to be executed.

Syntax

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

This is the means by which it works:

  • The switch articulation is assessed once.
  • The estimation of the articulation is contrasted and the estimations of each case.
  • If there is a match, the related square of code is executed.

Example

The getDay() technique restores the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2 ..)

Use the weekday number to compute weekday name:

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;
}

The aftereffect of day will be:

Try it yourself »

The break Keyword

When the JavaScript code translator comes to a break catchphrase, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.


The default Keyword

The default catchphrase indicates the code to run if there is no case match:

Example

The getDay() technique restores the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), compose a default message:

switch (new Date().getDay()) {
    case 6:
        content = "Today is Saturday";
        break;
    case 0:
        content = "Today is Sunday";
        break;
    default:
        content = "Looking forward to the Weekend";
}

The aftereffect of content will be:

Try it yourself »

Common Code and Fall-Through

Now and again, in a switch square, you will need diverse cases to utilize the equivalent code, or fall-through to a typical default.

Note from the following model, that cases can have a similar code square, and that the default case does not need to be the last case in a switch block:

Example

switch (new Date().getDay()) {
    case 1:
    case 2:
    case 3:
    default:
        content = "Looking forward to the Weekend";
        break;
    case 4:
    case 5:
       content = "Soon it is Weekend";
        break;
    case 0:
    case 6:
       content = "It is Weekend";
}
Try it yourself »