Include an “or” Operator in a JavaScript Switch Statement

I came across a situation where I needed a switch statement in JavaScript to do the exact same thing in multiple cases. For example:

switch (varAnimal)
{
   case ‘dog’:
   sameFunction();
   break;

   case ‘cat’:
   sameFunction();
   break;

   case ‘bird’:
   sameFunction();
   break;
}

While the above code works, if you have a long list of variables it is highly inefficient. To solve the problem I initially tried to use an “or” operator to try and test for the different values as you would do in an “if” statement. For example:

switch (varAnimal)
{
   case ‘dog’ || ‘cat’ || ‘bird’:
   sameFunction();
   break;
}

However this didn’t work. I found on a forum the below method which appears to accomplish what I was trying to do. It essentially lets you use an “or” operator to test for multiple cases which can save a lot of typing. For example:

switch (varAnimal)
{
   case ‘dog’: case ‘cat’: case ‘bird’:
   sameFunction();
   break;
}

Source: http://www.webdeveloper.com/forum/showthread.php?t=191879

Comments are closed.