Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

JavaScript Switch

The switch is a conditional statement like if statement. Switch is useful when you want to execute one of the multiple code blocks based on the return value of a specified expression.

switch(expression){
case 1:
//code to be executed
break;
case 2:
//code to be executed
break;
case 3:
//code to be executed
break;
case n:
//code to be executed
break;
default:
//default code to be executed
//if none of the above case executed
}

Use break keyword to stop the execution and exit from the switch. Also, you can write multiple statements in a case without using curly braces .

As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated. The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.

Example of switch statement:
var a = 4;
switch (a) {
case 1:
alert('case 1 executed');
break;
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}

In the above example, switch statement contains a literal value as expression. So, the case that matches a literal value will be executed, case 4 in the above example.

The switch statement can also include an expression. A case that matches the result of an expression will be executed.

Example: switch with string type case
var str = "lavu";
switch (str)
{ case "lavu":
alert("This is lavu");
case "sona":
alert("This is sona");
break;
case "lovely":
alert("This is lovely");
break;
default:
alert("Unknown Person");
break;
}

Example of combined switch cases
var a = 2;
switch (a) {
case 1:
case 2:
case 3:
alert("case 1, 2, 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}


Points to remember

  • The switch is a conditional statement like if statement.
  • A switch statement includes literal value or is expression based
  • A switch statement includes multiple cases that include code blocks to execute.
  • A break keyword is used to stop the execution of case block.
  • A switch case can be combined to execute same code block for multiple cases.