Javascript: Switch Case



Switch case is used as an alternative to if-else-elseif. Switch case is a conditional statement used to perform different actions based on different conditions and in Javascript works similar to PHP Switch case.

JavaScript Switch Case Syntax

Javascript switch case syntax is similar to php switch case. As an example below, we switch based on condition:

switch(val)
{
case 1:
  alert("executing case 1");
  break;
case 2:
  alert("executing case 2");
  break;
default:
  alert("executing default case");
}

The above code is equivalent to javascript if-then-else below:

if (val == 1) {
alert("executing case 1");
} else if (val == 2){
alert("executing case 2");
} else {
 alert("executing default case");
}