DEV Community

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

Posted on • Edited on

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

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'
  }
}
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (5)

Collapse
 
marlo22 profile image
marcin93

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.

Collapse
 
guilhermetoti profile image
Guilherme Toti

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!

Collapse
 
juliang profile image
Julian Garamendy

I prefer a ternary operation for this

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

or

const buttonColor = (active) => active ? 'orange' : 'blue'
Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
dpkahuja profile image
Deepak Ahuja 👨‍💻

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.