1

I have switch case like as below

  switch(something){
      case 1:
             break;
      case 2:
             break;
      case 3:
             break;
      default:
             break;
    }

Now i want to call case 1 within case 3 is it possible?

0

5 Answers 5

8

Just wrap the operations in functions so they are reusable

switch (something) {
case 1:
    operation1();
    break;
case 2:
    operation2();
    break;
case 3:
    operation3()
    operation1(); //call operation 1
    break;
default:
    defaultOperation();
    break;
}
Sign up to request clarification or add additional context in comments.

4 Comments

this is the best answer as fall-through cases get messy.
@jbabey if you are not gonna fall-through somewhere, you might as well not use switch, you can use an object literal with a key for each function
@Esailija Why not posting your solution using the object literal?
@OliverWeiler because object literal only works well when you don't need to fall through anywhere
2

You could do it like so:

switch(something){
  case 2:
         break;
  case 3:
         //do something and fall through
  case 1:
         //do something else
         break;
  default:
         break;
}

normally all code below a matched case will be executed. So if you omit the break; statement, you will automatically fall through to the next case and execute the code inside.

Comments

2
  switch(something){
      case 3:
      case 1:
             break;
      case 2:
             break;

      default:
             break;
    }

this should do the trick

Comments

1

combine the two cases:

switch(something){
   case 1:
   case 3:
          break;
   case 2:
          break;
   default:
          break;
 } 

Comments

1
var i = 3;

switch (i)
{
    case(3):
    alert("This is the case for three");

    case(1):
    alert("The case has dropped through");
    break;
    case(2):
    alert("This hasn't though");
    break;
}  

Not really a good idea though, leads to unreadable code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.