Javascript: Switch Case

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


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





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.