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.
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)) : }
Yes, you can use inner switch like this way,
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;`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With