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

Is 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 look at the same with if, else if e 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 in both ways.

Wouldn't

And else if have only semantic effect?

Author: Maniero, 2014-11-23

4 answers

In your example, it doesn't really make a difference, for two reasons:

  1. There are no two conditions that can be met at the same time.
  2. 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 run, as it has already entered the if (else means "otherwise"). Blocks of else and else if only execute if none of the above conditions have been met. Contrast with 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 they are two independent conditions and the number 100 meets both.

 36
Author: bfavaretto, 2014-11-23 00:54:20

Semantics

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

Simplicity

You should always try to use as simple as possible. I consider the simplest is the if with simple block (just one command), no extra conditionals or counter conditionals.

How does Block if

But there are cases in that this is not possible. When you have a situation where one action block is exclusionary in relation to the other, you need to use the else. Well, you don't actually have to. You can put a second if next with the condition reversed, but this doesn't make much sense, it worsens reading and maintenance.

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

Which is better

So yes, in your example you should make Choose else if mainly for the sake of semantics. But this is not something silly that only serves to meet one rule. It really makes it easy to read and tinker with your code without causing problems in the future.

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

Making separate ifs 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 simple if, it is not simpler to read a code so.

In addition to the question of if

But there is another problem. I wouldn't say your two codes do the same thing. They are not equivalent. Yeah, they're even the way it's written. But no one writes code like that except to exemplify.

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 put on GitHub for future reference .

In a real code there could be a situation that the variable bola does not none of these texts are worth it. Your code will execute chutar() 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, they will both do the same thing.

Notice bfavaretto's answer that shows that there may be another problem when you choose the option of isolated ifs. In your example it does not cause 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 the if will give unexpected result, it will be able to execute the two blocks and it is not what you want.

Conclusion

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


I think there is yet another problem in the code that doesn't seem so relevant to the question (but it may be) and that I'm just guessing since this is not real code. In the third case you are running the function chutar() but you are not returning the result of this function. In the previous conditions you are returning the result of the function. It may not have worked at all. That wouldn't make a difference.

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

Last I prefer to give a space between the if and the ( of the condition so as not to confuse it with a function call if.

 26
Author: Maniero, 2020-06-11 14:45:34

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

Here you cannot have any statement after the one 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 one can do something after the correct action has been chosen (but returning a value is more "boring"):

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 one 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. To determine which is the" simplest", or" most correct", or" easiest to maintain "(and much from time to time" most efficient"), just thinking about the code as a whole - and not just focusing on the particular excerpt in which the conditions are tested.

 13
Author: mgibsonbr, 2014-11-23 03:50:42

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, all 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 upon returning a value, the rest of the code does not execute.

 11
Author: Guilherme Portela, 2014-11-23 00:26:00