Jackson
Jackson

Reputation: 1524

How to call case within switch case using javascript?

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?

Upvotes: 1

Views: 3413

Answers (5)

sithereal
sithereal

Reputation: 1686

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

      default:
             break;
    }

this should do the trick

Upvotes: 2

Jeff Watkins
Jeff Watkins

Reputation: 6359

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

Upvotes: 1

Ray
Ray

Reputation: 21905

combine the two cases:

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

Upvotes: 1

devsnd
devsnd

Reputation: 7722

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.

Upvotes: 2

Joseph
Joseph

Reputation: 119867

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

Upvotes: 8

Related Questions