0

Is it possible to add all the cases in the following code together, since they will execute the same function? (Javascript)

what I have:

function blabla(x){

switch (x){
case 1:
case 2:
case 3:
return "hello";}

}

what I want:

function blabla(x){

switch (x){
case /*1,2 and 3 together in only one case*/:

return "hello";}

}
  • When you were asking your question, there was a big orange **How to Format** box to the right of the text area with useful information in it. There was also an entire toolbar of formatting aids. And a **[?]** button giving formatting help. *And* a preview area located between the text area and the Post Your Question button (so that you'd have to scroll past it to find the button, to encourage you to look at it) showing what your post would look like when posted. Making your post clear, and demonstrating that you took the time to do so, improves your chances of getting good answers. – T.J. Crowder Aug 16 '17 at 17:07
  • so is it possible to do case 1|| 2 || 3: as well? – Shaky Edits Aug 16 '17 at 17:12
  • You can use any valid expression, so `switch (true)` with `case x == 1 || x == 2 || x == 3` would work. But it's ugly. – T.J. Crowder Aug 16 '17 at 17:14
  • You could also just avoid the switch altogether i.e. var cases = { 1: function() {/*do some stuff*/}; }; cases.1 = cases.2 = cases.3; – Link0352 Aug 16 '17 at 17:16
  • 1
    @Link0352: Indeed. (You need brackets notation for those latter assignments, but the linked question's answers do indeed discuss using dispatch objects.) – T.J. Crowder Aug 16 '17 at 17:20
  • @T.J Crowder My mistake. Got excited to answer a question and didn't notice the link. Thanks for the input! – Link0352 Aug 16 '17 at 17:23

0 Answers0