Question on Else If and Switch Statements

I just finished “Replacing If Else Chains with Switch” exercise. It shows how you can replace if else statements with switch statements. It said it was easier, but it seems like six of one, half a dozen of the other to me. How does using switch statements make it easier? It seems to me that there are just as many lines of code, so what’s the reason behind changing to switch statements.

Sometimes, the choice comes down to how readable the code is to other people. Switch statements can clean up your code when you have a lot of options. Here’s something I wrote using switch/case instead of if/else:

function getMonthFromWord(word) {
    word = word.slice(0,3).toLowerCase();
    switch(word) {
        case "jan":
            return "January";
        case "feb":
            return "February";
        case "mar":
            return "March";
        case "apr":
            return "April";
        case "may":
            return "May";
        case "jun":
            return "June";
        case "jul":
            return "July";
        case "aug":
            return "August";
        case "sep":
            return "September";
        case "oct":
            return "October";
        case "nov":
            return "November";
        case "dec":
            return "December";
            return false;

Switch/case are also more than mere replacements for if/else clauses. If you omit the break statement, your code will drop down to the next case, which can be exactly what you want.

switch(x) {
    case "a":
      //Do one thing and stop
    case "b":
       //We want to do two things, so no break
    case "c":
      //This code will execute if "b" or "c" is true, but if x === "c", we won't get case "b"
     //Easy default case

This would be much harder to do with if/else.

1 Like

Thanks. Understanding how to do something and when to do something are two different things. I often find that I’m only getting the how and not the when with online training.

It comes with experience. That feeling of uncertainty means you’re learning. Just keep doing what you’re doing!


Its also a matter of performance.

An if/else if statement is a branching statement, that is the browser must read the code and decide which branch its going to take. Its making a decision, like choosing a path. This is expensive in terms of CPU and resources so as such should be kept to a minimum.

I hope that helps



Thanks PortableStick and Markj78. Your information really helps me to start to understand when to use which type of coding. Too bad if and else if statements should be kept to a minimum, I’m really good at them and they are fun to create.:slight_smile:

of course, thay have their place and as we progress through the curriculum we are sure to better understand the why’s and what-for’s of Javascript :slight_smile: