loading...
Cover image for You don't always need “else” in your "if"

You don't always need “else” in your "if"

guilhermetoti profile image Guilherme Toti Updated on ・1 min read

Hey guys!

The most basic stuff you learned about programming, I think, is if…else. Am I right?

What if I say you don’t always need the else?
There are cases where the else is unnecessary, and your code becomes more readable without it!

Let’s see an example — let’s say you have a function like this:

function buttonColor(active) {
  if (active) {
    return 'orange'
  } else {
    return 'blue'
  }
}

So, if the parameter active is true it will return orange, otherwise it will return blue.

This is a case where you don’t need the else, let’s see the same function without it:

function buttonColor(active) {
  if (active) {
    return 'orange'
  }

  return 'blue'
}

Even if the previous one is easy to understand, it looks easier now, right?

So, if you have an if…else and you don’t check anything on the else, there is no reason to keep the else and return it instead.

I don’t know you, but, I have the feeling that with if…else I have to kinda “re-read” it to understand, while without else it’s more clear what is happening there.

That’s all, folks!
I hope you enjoy this quick tip!

Posted on May 22 by:

guilhermetoti profile

Guilherme Toti

@guilhermetoti

A friendly guy who loves coding and photography.

Discussion

markdown guide
 

This is nice tip! In this case else statement is totally unnecessary and avoid it can improve code readability. If I'm not wrong ESLint can help respect this, because it has rule no-return-else or something like that.

 

Thanks man! Yes, the idea is to improve code readability!
Oh, I don’t know about this ESLint rule, but it can be very helpful!

 

I prefer a ternary operation for this

function buttonColor(active) {
  return active ? 'orange' : 'blue'
}

or

const buttonColor = (active) => active ? 'orange' : 'blue'
 

Yeah, me too, for sure!
But the idea of this post was just to show that we don't need to always use else, that's why I didn't use the ternary operation there

 

Yes helpful because it reduced the code branch by 1 and also indentation is reduced. The read to write code ratio is like 10:1, hence it makes a big difference while reading code.