Nested switch statement in javascript

Is it possible to use a nested switch statement in javascript.

My code is like

 switch(id1) { case 1: switch(id2){ case 1:{ switch(id3){ case 1:{} case 2:{} } } case 2:{ switch(id4){ case 1:{} case 2:{} } } } case 2: } 

If so, then this is good practice, or we can use any alternative approach.

+5
source share
4 answers

Your approach is absolutely perfect.

You can make switch placement less complicated by using switch (true) :

 switch (true) { case ((id1 === 1) && (id2 === 1) && (id3 === 1)) : case ((id1 === 1) && (id2 === 1) && (id3 === 2)) : case ((id1 === 1) && (id2 === 2) && (id3 === 1)) : case ((id1 === 1) && (id2 === 2) && (id3 === 2)) : case ((id1 === 2) && (id2 === 1) && (id3 === 1)) : case ((id1 === 2) && (id2 === 1) && (id3 === 2)) : case ((id1 === 2) && (id2 === 2) && (id3 === 1)) : case ((id1 === 2) && (id2 === 2) && (id3 === 2)) : } 
+10
source

Yes, you can use the internal switch in this way

Please check this demo: https://jsfiddle.net/1qsfropn/3/

 var text; var date = new Date() switch (date.getDay()) { case 1: case 2: case 3: default: text = "Looking forward to the Weekend"; break; case 4: case 5: text = "Soon it is Weekend"; break; case 0: case 6: switch(date.getFullYear()){ case 2015: text = "It is Weekend of last Year."; break; case 2016: text = "It is Weekend of this Year."; break; case 2017: text = "It is Weekend of next Year."; break; default: text = date.getDay(); break; } break; } document.getElementById("demo").innerHTML = text;` 
+1
source

You can use the nested switch statement, but it can quickly become spaghetti code, and therefore is not recommended. I would rather use functions with a nested switch statement to encode the code, or perhaps use a recursive function depending on what the code should do.

This is just pseudo code, but I hope this gives you an idea of ​​how to implement it. You must be careful to stop recursion at some given id value. This pseudo-code increases the value of the identifier by 1 if the ID value is 1 and increases by 2 if the value is 2. If the value is not 1 or 2, the recursion is completed.

 function recursiveSwitch(var id) { switch(id) { case 1: recursiveSwitch(id + 1); break; case 2 recursiveSwitch(id + 2) break; default: return; } } 
+1
source

In principle, this is possible, but I think it depends on the complexity of nesting if he recommended using a nested switch statement or using functions with a nested switch statement, as suggested by Omar Oscarsson.

0
source

All Articles