IF, ELSE IF, ELSE or IF IF IF. When to use, what's the difference?

33

It's a very basic question, but it intrigues me a lot. See the code below:

var bola = "redonda";
if(bola == "comestivel") return comer();
if(bola == "liquida") return beber();
if(bola == "redonda") chutar();

Now see the same with if , else if and else

var bola = "redonda";
if(bola == "comestivel") return comer();
else if(bola == "liquida") return beber();
else chutar();

That is, the same end can be obtained both ways.

Would not the else if and else have only a semantic effect?

    
asked by anonymous 23.11.2014 / 01:18

4 answers

33

In your example, it does not really matter, for two reasons:

  • There are not two conditions that can be met at the same time.
  • You always return when you enter one of the if , and the following do not execute
  • Now consider the following example:

    var numero = 100;
    if(numero <= 100) {
        console.log("menor ou igual a 100");
    } else if(numero < 1000) {
        console.log("menor que 1000");
    }
    

    The else will not be executed, since it has already entered if ( else means "otherwise"). Blocks of else and else if only execute if none of the previous conditions has been met. Contrast this:

    var numero = 100;
    if(numero <= 100) {
        console.log("menor ou igual a 100");
    } 
    if(numero < 1000) {
        console.log("menor que 1000");
    }
    

    Here both are executed, since there are two independent conditions and the number 100 caters to both.

        
    23.11.2014 / 01:29
    25

    Semantics

    Programming languages often have different constructs to give different semantic effects. You rarely need a different build if you do not want this result.

    Simplicity

    You should always try to use as simple as possible. I think the simplest is if with simple block (just a command), without extra conditionals or against conditional.

    How it works block if

    But there are cases where this is not possible. When you have a situation where one block of action is mutually exclusive, you must use else . Well, you do not really need to. You can put a second if next with the inverted condition, but this does not make much sense, it makes reading and maintenance worse.

    This also applies when you have a series of mutually exclusive options, that is, only one is valid. You can even make multiple% s of% s, but if the decision is interconnected, if it is more logical that it be done as a single operation it is better to choose it.

    What's best

    So yes, in your example you should make choosing if primarily because of semantics. But this is not something silly that only serves a rule. It really makes it easy to read and tweak your code without causing problems in the future.

    Codes should be written primarily for humans to read. So it is very helpful to give the correct understanding of what you are doing there. When all the choices lead to the same place choose the simpler . We can adapt this statement for the purpose of maintenance: if all forms solve the problem, choose the one that best expresses your intention.

    Making% of separate% s that are logically connected passes the wrong idea. My understanding is that your code is making a single logical decision. Even though it is simpler to use else if simple, it is not easier to read such code.

    Beyond the question of if

    But there is another problem. I would not say your two codes do the same thing. They are not equivalent. Okay, they're even the way it's written. But no one writes code like that except for example.

    var bola = "redonda";
    if (bola == "comestivel") return comer();
    if (bola == "liquida") return beber();
    if (bola == "redonda") chutar();
    

    and

    var bola = "redonda";
    if (bola == "comestivel") return comer();
    else if (bola == "liquida") return beber();
    else if (bola == "redonda") chutar();
    

    are equivalent.

    I placed GitHub for future reference .

    In a real code there could be a situation where the variable if is not worth any of these texts. Your code will execute if if the text is different from the two initial options in the second code, but will not execute in the first if the first situation is the same. In the above code, both will do the same thing.

    Notice the response from bfavaretto that shows that there may be another problem when you choose the option of bola s insulated. In your example it does not cause a problem, but when you can have two conditions being met and you want only one block to be executed (are mutually exclusive, or executes one or the other), separating chutar() will give unexpected result, it can execute the two blocks and it's not what you want.

    Conclusion

    So finding the simplest is tricky. It is common for less experienced programmers to do extremely complicated things because they do not know how to do simple. It seems a contradiction but it is what happens the most. The simplest in these cases is the structure that seems more complicated (not that much).

    I think there is still another problem in the code that does not seem so relevant to the question (but it may be) and I'm only guessing since this is not a real code. In the third case you are running the if function but it is not returning the result of this function. In the previous conditions you are returning the result of the function. It may not have worked. That would make no difference.

    Even though I would still put if at the end unless you have a reason not to. It's a question of symmetry. If the intention is to terminate the function there, explicitly state that you will do this. If the intention clearly does not need to return a value in any case, you should then take out all chutar() to make it clear that you are not returning a value. Or at least call the function and only then use return chutar() .

    Finally I'd rather give a space between return and return of the condition to not confuse with a function called if .

        
    23.11.2014 / 01:34
    13

    The other answers already explain very well, but I would like to complement with the following: there are often several ways of doing the same thing, without there being clearly a "better" or "worse", so it is up to you - by your experience or your feeling - decide which one to use on a case-by-case basis.

    Here you can not have any statement after that being chosen (without repeating code):

    if(bola == "comestivel") return comer();
    if(bola == "liquida") return beber();
    if(bola == "redonda") return chutar();
    return nenhumaDasAnteriores();
    
    qualquerUmaDelas(); // Nunca executará
    

    Here you can do something after the correct action has been chosen (but returning a value is more "annoying"):

    if(bola == "comestivel") comer();
    else if (bola == "liquida") beber();
    else if (bola == "redonda") chutar();
    else nenhumaDasAnteriores();
    
    qualquerUmaDelas(); // Seja o que for feito, isso será feito depois
    

    Here you can do the same thing with two or more different conditions (or two or more things with the same condition):

    switch(bola) {
        case "redonda":
        case "oval":
            chutar(); // redonda ou oval, chuta
            break;
        case "comestivel":
            comer(); // comestível, só come
            break;
        case "sorvete":
            comer(); // sorvete derretendo, come...
        case "liquida":
            beber(); // ...depois bebe; liquida, só bebe
            break;
        default:
            nenhumaDasAnteriores();
    }
    

    Here you can change the conditions dynamically:

    var acoes = {
        comestivel:comer,
        liquida:beber,
        redonda:chutar
    }
    
    var fn = acoes[bola] || nenhumaDasAnteriores;
    fn();
    
    ...
    
    acoes.leve = arremessar;
    

    Etc. In order to determine which is the "simplest," or "most correct," or "easier to maintain" (and often "more efficient") thinking of the code as a whole - not just concentrating on the particular section in which the conditions are tested.

        
    23.11.2014 / 04:50
    11

    There is a functional effect: in a conditional structure, when one block is executed, the others are ignored.

    That is, in the first example, there are three conditional structures, while in the second, there is a conditional structure divided into three blocks. In the first example, the three structures are executed; while in the second, if one is executed, the others will be ignored (without wasting time checking unnecessarily the conditions of the arguments).

    In this case, I believe there is no difference, because apparently this code is inside a function, and when returning a value, the rest of the code is not executed.

        
    23.11.2014 / 01:26