Can I somehow use if statement in switch to add more cases?

I am trying to write a switch statement, but I have a strictly defined case, and I want to use as little code as possible. Since I was wondering how to do this, it occurred to me whether it would be possible to add an if statement to a switch, so if this if statement is true, to add more cases to my switch. For instance:

switch(myVar) { case 1: return 'Your variable is 1'; case 2: return 'Your variable is 2'; if(yourVar && yourVar === true) { case 3: return 'Your variable is 3'; } default: return 0; } 

PS The real scenario I'm using is more complicated and the code is really long, so any greetings are welcome if they are suitable for use.

+6
source share
4 answers

Perhaps you move your logic a bit. You can omit the break statement because you end the function with return .

 switch(true) { case myVar === 1: return 'Your variable is 1'; case myVar === 2: return 'Your variable is 2'; case yourVar: return 'Your variable is 3'; default: return 0; } 
+2
source

Move the test inside the case and fail if it fails:

 switch(myVar) { case 1: return 'Your variable is 1'; case 2: return 'Your variable is 2'; case 3: if (yourVar) return 'Your variable is 3'; /* fall through */ default: return 0; } 
+2
source

You can do it

 function test(myVar, yourVar) { switch(myVar) { case 1: return '1'; case 2: return '2'; default: // as requested in a comment, add yourVar to myVar if(myVar != undefined && yourVar != undefined) return myVar + yourVar; return '0'; } } alert(test(2)); alert(test(3)); alert(test(3,5)); alert(test(3,0)); 
+1
source

 switch(myVar) { case 1: return 'Your variable is 1'; case 2: return 'Your variable is 2'; case 3: if(yourVar && yourVar === true) { return 'Your variable is 3'; }else{ return 0: } default: return 0; } 
0
source

All Articles