Quote:
Originally Posted by kazana
Curious about that statement. Can you give me an example that could not be done with a switch statement?
Aesthetics aside, I cannot think of an if/elseif/.../else or ternary example that cannot be done with switches.
any if / else if / else chain where the conditions for the different blocks are non-simple.
if you had something like
Code:
if (a == 5) {
return 5
} else if (a == 6) {
return 6
} else {
return
}
That can be easily represented with a switch
Changing the block conditions a little makes it pretty silly to represent with a switch. You could of course but its not pretty and not really what switches are meant for.
Code:
if (a == 5 && b == 10) {
return 5
} else if (a == 6 && b == 15) {
return 6
} else {
return
}
This is how you might represent the above with a switch.
Code:
switch (a) :{
case 5 :
return b == 10 ? 5 : void 0
case 6 :
return b == 15 ? 6 : void 0
default :
return
}
Ternary for that
Code:
return a == 5 && b == 10 ? 5 : a == 6 && b == 15 ? 6 : void 0
Basically, switches are only really meant for blocks with exceedingly simple conditions. You can of course figure out how to implement a switch for blocks with complex conditions but it doesn't really make sense to.
My rule of thumb generally is this :
1) Simple logic inside the blocks ? ternary
2) Simple conditions inside the block and non-simple logic inside the block ? if / else or switch (comes down to style)
3) Complex conditions inside the block and complex logic inside the block ? if / else
Last edited by Craggoo; 06-22-2016 at 12:44 AM.