JavaScript Switch Statement

The switch statement is used to perform different actions based on different conditions.

The JavaScript Switch Statement

Use a switch statement to select one of multiple blocks of code to execute.


switch (n) { case 1: Execute code block 1 break; case 2: Execute code block 2 break; default: Code executed differently than case 1 and case 2 }
How it works: First set the expression n (usually a variable). The value of the expression is then compared with the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use break to prevent the code from automatically running to the next case.


Displays today's day of the week. Please note Sunday = 0, Monday = 1, Tuesday = 2, etc .:
var d = new Date (). getDay (); switch (d) { case 0: x = "Today is Sunday"; break; case 1: x = "Today is Monday"; break; case 2: x = "Today is Tuesday"; break; case 3: x = "Today is Wednesday"; break; case 4: x = "Today is Thursday"; break; case 5: x = "Today is Friday"; break; case 6: x = "Today is Saturday"; break; }

Running result of x:

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

Use the default keyword to specify what to do when a match does not exist:


If today is not Saturday or Sunday, the default message is output:

var d = new Date (). getDay (); switch (d) { case 6: x = "Today is Saturday"; break; case 0: x = "Today is Sunday"; break; default: x = "looking forward to the weekend"; } document.getElementById ("demo"). innerHTML = x;

Running result of x:

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:


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