Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested switch statement in javascript

Is it possible to use nested switch statement in javascript.

My code is some what look 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 yes then it is a good practice to do or we can use any alternate approach.

like image 561
shanky singh Avatar asked Jul 14 '16 09:07

shanky singh


2 Answers

Your approach is absolutely fine.

You can make the switch nesting less complex 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)) : } 
like image 191
Rounin - Glory to UKRAINE Avatar answered Oct 05 '22 01:10

Rounin - Glory to UKRAINE


Yes, you can use inner switch like 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;` 
like image 29
Joey Etamity Avatar answered Oct 05 '22 01:10

Joey Etamity