This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Jeffrey Wan
over 9 years

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

0 votes

Permalink

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

points
Submitted by tony de araujo
over 9 years

Answer 5429b252548c357261005681

0 votes

Permalink

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.

points
Submitted by Roy
over 9 years