Tuesday, 15 August 2017

Switch statement multiple cases in JavaScript



I need multiple cases in switch statement in JavaScript, Something like:



switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;


default:
alert('Default case');
break;
}


How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows DRY concept.


Answer



Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:




switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;

default:

alert('Default case');
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...