This forum is now read-only. Please use our new forums at discuss.codecademy.com.

408 points

Submitted by
Jeffrey Wan
over 5 years ago

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!"
    }

};

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

--

2955 points

Submitted by
tony de araujo
over 5 years ago


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.

9070 points

Submitted by
Roy
over 5 years ago