Switch statements vs if/else if/else conditionals. What's the difference?
Are switch statements really that much more simple than using if/else if/else structure? Why is it that CodeAcademy views switch statements as a simpler alternative. Switch cases seem a lot like else if conditional branches. Yes or no? Does that make sense?
var getReview = function (movie) {
switch(movie) {
case "Toy Story 2":
return "Great story. Mean prospector."
case "Finding Nemo":
return "Cool animation, and funny turtles."
case "The Lion King":
return "Great Songs."
default:
return "I don't know!"
}
};
Answer 5429ac498c1ccc3cf4005624
Hi Jeffrey, the following was taken from Wikipedia rather than trying to write it myself: “
Easier to debug (e.g. setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability)
Easier to read (subjectively)
Easier to understand, and therefore
Easier to maintain
Fixed depth: a sequence of “if else if” statements yields deep nesting, making compilation more difficult (especially in automatically generated code) Faster execution potential “
en.wikipedia.org/wiki/Switch_statement
–
Answer 5429b252548c357261005681
If-else conditional branches are great for variable conditions that net a boolean, whereas switch statements are great for fixed data values that net a return value. The switch above is a perfect example of fixed data with mapped return values. An if-else conditional in this instance would be very cumbersome and clumsy.