What is the point of else statements?

What is the point of else statements?
0

#1

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?


#2

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.


#3

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?


#4

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”


#5

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Also, similar to @v-lai’s great example, you could also have something like this:

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

#6

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