What is the purpose of 'else if' statements?

Tell us what’s happening:

Hey guys. I can’t understand how the use of ‘else if’ and ‘else’ is any different than just using three ‘if’ statements? Doesn’t the function still work the same, eventually landing on one val which satisfies true or false and returns a statement?

Regards
matt

Your code so far


function testElseIf(val) {
if (val > 10) {
  return "Greater than 10";
}

else if (val < 5) {
  return "Smaller than 5";
}

else { return "Between 5 and 10";
}
}

testElseIf(7);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Introducing Else If Statements

Link to the challenge:

You can do the exact same thing with only ifs, it’s just shorter and more readable to use if-else.

Thanks for the reply.

but - surely they’d be the same length?

Matt

Code with if-else:

function testElseIf(val) {
  if (val > 10) {
    return "Greater than 10";
  } else if (val < 5) {
    return "Smaller than 5";
  } else {
    return "Between 5 and 10";
  }
}

Code with if only:

function testElseIf(val) {
  if (val > 10) {
    return "Greater than 10";
  } 
  if (val < 5) {
    return "Smaller than 5";
  } 
  if (true) {
    return "Between 5 and 10";
  }
}

You can also get some lengthy logical conditions if you want to make sure with only if statements that you only execute one of the blocks while with an if-else it happens automatically.

In this particular case, you could get the same result without else for two reasons:

  1. Every if block has a return statement, so nothing will be executed after it.
  2. val > 10 and val < 5 are mutually exclusive.

These are not always the case.

But even when leaving off the elses will get you the same result, using an else is both more efficient and easier to read. An else means “only bother to check this if the last thing was false”. An if on its own will always perform its check.

if (age >= 21) {
   response = "You can drink in the US";
}
if (age >= 18) {
    response = "You can vote, but not drink";
}
if (age >= 16) {
    response = "At least you can drive";
}
if (age < 16) {
    response = "You're just a child";
}
return response;
/* if age is 30
* this will give the response "At least you can drive".
* It will also perform 4 age checks
*/
if (age >= 21) {
   response = "You can drink in the US";
}
if (age < 21 && age >= 18) {
    response = "You can vote, but not drink";
}
if (age < 18 && age >= 16) {
    response = "At least you can drive";
}
if (age < 16) {
    response = "You're just a child";
}
return response;
/* if age is 30
* this one will return "You can drink in the US"
* but it will also do 4 age checks
* and it sucks to read
*/
if (age >= 21) {
   response = "You can drink in the US";
}
else if (age >= 18) {
    response = "You can vote, but not drink";
}
else if (age >= 16) {
    response = "At least you can drive";
}
else {
    response = "You're just a child";
}
return response;
/* if age is 30
* this will give the response "You can drink in the US"
* That is the only evaluation it will do
* It's also clear to see what the logic is
*/
3 Likes

else if makes your code check 1 of the conditions
so:

if(condition1) {
//codes here
}

if (condition2) {
//codes here 
}

It will check both condition. Example if condition1 is right, it will go to condition2 and check if its right. But using else if

if (condition1) {
//codes here
} else if (condition2) {
//codes here again
}

The code will check if condition1 is correct. If it is correct, then it runs the code and runs along without checking condition2. But if condition1 is wrong, it will go to the else if and check the condition2;

1 Like

Do note there’s a much less cluttered version:

if (age >= 21) return "You can drink in the US"
if (age >= 18) return "You can vote, but not drink"
if (age >= 16) return "At least you can drive"
return "You're just a child"

This flies in the face of many best practices for several reasons, but I’d argue that this is as clear as it gets. Each branch immediately returns so there’s no accidental fall-through. Every return is on the same line so you’re not likely to fall prey to the “adding a line” bug.

Mind you if I do that in my IDE, just hitting the reformat key will transform it all into the blocks-with-curlies notation anyway.

Oh, and there’s the ternary operator:

return (age >= 21) ? "go kill some brain cells!"
     : (age >= 18) ? "go vote!"
     : (age >= 16) ? "go cruising!"
     : "go away kid";

That’s not a “hack” or “code golf” either, it’s how the ternary operator is intended to work. I really do suggest using that table-style formatting though.

Right, though that only works because it’s an if statement with returns. If your if-else is in the middle of a function producing some intermediate results, then refusing to use an else statement can make your code messy and hard to read/maintain.

Yes indeed. This is called a guard clause. It makes it neat and is actually a lot more accurate then others, but it has its own disadvantages. It only works if you want to return something. But if you want to produce a function or run another function and such, it will not work.

I wouldn’t say its more accurate. It’s equally as accurate if it produces identical results.

1 Like

I’m a fan of return-early myself. I write most of my code in a functional style so there normally is only one return, but when I drop into an imperative style, I would rather make clearer the intentions that made me use that style in the first place, and that usually includes multiple return points.

The ternary table is a single expression if you prefer that.

I can return or call a function just as easily too. If the logic got any more complex or I needed additional imperative steps, I’d use the more verbose version from the start. As I said, my IDE will reformat that pretty code into the standard best-practice style anyway, so it’s really more about toy code than anything else.

Tried to specifically call out the fact that returning in an if makes a difference. My example is contrived and I was trying to limit it to concepts that someone would already have encountered already at this point in the curriculum. Of course, there are lots of uses of if/else logic that do not tie in to a return value. I was just trying to illustrate what omitting an else can mean.

2 Likes

Hey @matthurry, in the case you got a little confused, as I did, with @ArielLeslie last code snippet, here is the fix:

/* if age is 30               |    right response     | 
* this will give the response "You can drink in the US".
* That is the only evaluation it will do 
* It's also clear to see what the logic is 
*/

@ArielLeslie, don’t get wrong me please, it was a pretty good reply of yours.

1 Like

Thanks for catching my bad copy-paste. Fixed it.

1 Like

Else ifs or multiple ifs are just a preference. You could argue that else ifs are a bit more verbose, in a sense that you can read code easier, but I’ve rarely ever seen an else if.

Ahh… Those lovely IDEs

Hey - thanks for your reply, it’s super helpful and really clarified the difference for me. I suspect as i get more used to coding i’ll find more and more examples of this difference and it’ll become even cleared.

on the first example:

if (age >= 21) {
response = “You can drink in the US”;
}
if (age >= 18) {
response = “You can vote, but not drink”;
}
if (age >= 16) {
response = “At least you can drive”;
}
if (age < 16) {
response = “You’re just a child”;
}
return response;
/* if age is 30

  • this will give the response “At least you can drive”.

Wouldn’t it return a response of “You can drink in the US”? As age (in this case 30) >= 21?

Thanks again!
Matt

Nope. The function doesn’t stop until the return at the end and every true if statement evaluates.

1 Like
  • First it checks whether age is greater than or equal to 21.
    • It is
    • response is set to “You can drink in the US”
  • Then it checks whether age is greater than or equal to 18. – if there had been an else it wouldn’t have done this check, because the else means “If the last thing wasn’t true”.
    • It is
    • response is set to “You can vote, but not drink”
  • Then it checks whether age is greater than or equal to 16. (Doesn’t happen with an else
    • It is
    • response is set to “At least you can drive”
  • Then it checks whether age is less than 16. (Wouldn’t check with an else)
    • It is not