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

Asked

Viewed 58,476 times

36

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 watch 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 in both ways.

The else if and else wouldn’t just have semantic effect?

4 answers

36


In your example, it doesn’t really matter, 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 if, and the following do not

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 as it has entered the if (Else means "otherwise"). Blocks of else and else if perform only 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.

27

Semantics

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

Simplicity

You should always try to use as simple as possible. I consider that the simplest is the if single block (only one command), no extra conditionals or conditional.

How does block work if

But there are cases where this is not possible. When you have a situation where one action block is excluding from the other, you need to use the else. Well, actually you don’t have to. You can put a second if then with the condition reversed, but this does not make much sense, worsens the reading and maintenance.

This is also true when you have a number of mutually exclusive options, that is, that only one is valid. You can even make several ifs, 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 choose the else if mainly because of semantics. But this is not something silly that only serves to meet a rule. Really makes it easy to read and tinker with your code without causing problems in the future.

Codes should be written primarily for humans 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 to the purpose of maintenance: if all forms solve the problem, choose the one that best expresses your intention.

Do ifSeparate s that are logically connected gives the wrong idea. My understanding is that your code is making a single logical decision. Even though it’s simpler to use the if simple, it is no longer simple to read a code like this.

Beyond the question of if

But there is another problem. I would not say that 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 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 in the Github for future reference.

In a real code there could be a situation that the variable bola is not worth any of these texts. 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 code above, both will do the same thing.

Note the response of bfavaretto that shows that there may be another problem when choosing the option of ifs isolated. In your example no problem, but when you can have two conditions being met and you want only one block to run (are mutually exclusive, or runs one or the other), separate the if will give unexpected result, it can run the two blocks and is not what you want.

Completion

Because finding the simplest is complicated. It’s common for less experienced programmers to do extremely complicated things because they don’t know how to do simple. It seems a counter-intuitive but it is what happens most. The simplest in these cases is the structure that seems more complicated (not that it is much).


I think there is yet another problem in the code that doesn’t seem so relevant to the question (but could be) and that I’m just intuiting since this is not real code. In the third case you are running the function chutar() but is not returning the result of this function. In the previous conditions you are returning the result of the function. Maybe it didn’t work out anyway. Then it wouldn’t matter.

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

Finally I prefer to give a space between the if and the ( condition not to be confused with a function called if.

  • I would complement with: var ball = "round"; if (ball == "edible"){ Return eat(); }Else if (ball == "net"){ Return drink(); } //neither and we don’t need to do other checks? Return kick();

13

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 it is up to you - by your experience or by your feeling - decide which one to use on a case-by-case basis.

Here you cannot have any instruction 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 you 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 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. To determine which is the "simplest", or "most correct", or "easiest to maintain" (and very often "most efficient"), only thinking of the code as a whole - and not only focusing on the particular section where the conditions are tested.

12

There is a functional effect: in a conditional structure, when a 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 unnecessarily checking the conditions of the arguments).

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

  • 1

    Then a if-else if has a performance gain by ignoring the rest?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.