What is the point of else statements?

I feel like I’m missing something with else statements. Maybe it’s the way the challenges are structured or maybe I’m just not getting it but it looks to me like you would get the same result not including the else statements as if you did. For example, in the “Else if” challenge this is the code they want you to write to pass:

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

But if I get rid of the else statements and test the code as follows it functions just fine without the else statements.

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

If I test 0 I get “smaller than five.” If I test five I get “Between 5 and 10” and if I test 12 I get “Greater than 10” etc etc. So, why use else statements when excluding them seems to create the same result? Is there an aspect of them I have yet to learn?

1 Like

You’re right in that you might not need an else statement. However, that example isn’t good for else statements is because you’re returning something. When you return something, you stop executing anything after that line. If we had used a different example where you might have multiple if and else if statements prior to returning, you may need an else - it really depends on the problem.

1 Like

Hi, thanks for your answer. If it’s not too much trouble could you provide a simple example where an else statement would be required?

1 Like

The simplest example would be if you wanted to console.log() values instead of return.

function testElseIf(val) {
  if (val > 10) {
    console.log( 'Greater than 10');
  } else if (val < 5) {
    console.log( 'Smaller than 5');
  } else {
    console.log( 'Between 5 and 10');
  }
}

because if you try values less than 5 you get both “Smaller than 5” and “Between 5 and 10” or if you choose a value greater than 10 you will get both the “Greater than 10” and “Between 5 and 10”

1 Like

you use “else if” to tie comparisons, “else” is used to execute some code when the previous comparison returned a false condition.

1 Like