If Statements

Efficient Usage

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

if (someCondition) {
   // 10 lines of code
} else {
   // More 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..

If-else statements get used a lot to assign variables

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
}

There’s a way to optimize this code even more. We could make this piece of code a one-liner by using the conditional operator:

number = someCondition ? someNumber * 2 : 1;

Guard Clauses are also known as early-returns.

The idea behind returning early is that you write functions that return the expected positive result at the end of the function.

The rest of the code, in the function, should trigger the termination as soon as possible in case of divergence with the function’s purpose.

An early return does exactly as its name implies. This is what an early return looks like:

function someFunction() {
    if (!someCondition) {
        return;
    }    
    // Do something
}



Backlinks