Back
You don't always need “else” in your "if"
Published On: May 22
#javascript#codenewbie#codequality

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!

Dev.to