We use else clauses in our code all the time. Out of habit and without giving it too much thought most likely. Else clauses seem so integrated into our arsenal of skills to solve coding problems. Once you start learning how to program one of the first concepts you’re going to learn about is the if-else statement.

Using else in your code seems so harmless, but is it really?

When you give a little more thought to your code you’ll realize most of these else blocks are redundant. All these redundant else blocks do to your code is make it unnecessarily long, less readable, and seem more complex than it actually is.

Although code can still be quite readable when a single if-else statement gets used. It tends to get much worse really fast. When using another if-else statement in the else block of the first if-else statement for example. Once you need a construction like this you should probably refactor the code.

If we know how to get rid of these else blocks the code will get easier to read. On top of that, there will be a single path of truth which makes your code much more understandable for other developers.

That’s why we’re going over four ways you could use to avoid else blocks in your code. The best part about these alternatives is that they make your code more elegant.


Using returns

The most classic form of the if-else statement looks really simple.

if (someCondition) {
   // 10 lines of code
} else {
   // More code..
}

No rocket science involved here. It’s safe to say that every programmer has written code that looks like this before. Most programmers write code like this on a daily basis without giving it too much thought.

But what would the code look like if we get rid of that else block?

Instead of using an else block, we could choose to use a return. This will help get rid of the else block and avoid unnecessarily indented code.

This is how we could use a return in order to get rid of the else block:

if (someCondition) {
   // 10 lines of code
   return;
} 
// More code..

When making use of a return the else block gets redundant.


Using default values

If-else statements get used a lot to assign variables — which makes no sense. You’ve probably seen code like this before:

if (someCondition) {
   number = someNumber * 2
} else {
   number = 1
}

When you spot code like this, change it. The way to get rid of the else block is by assigning a default value.

number = 1

if (someCondition) {
   number = someNumber * 2
}

Looks much better, right?

#software-development #programming #javascript #web-development #technology

How You Can Avoid Using Else in Your Code
1.10 GEEK