May 23, 2023

Early return pattern in javascript

In javascript, there is always scope of writing good quality of code. Let’s understand how early return helps writing good quality of code.

what is early return?

Early return is nothing but the simple way to return a function as soon as the result available

Early return helpful in

  • removing unnecessary else statements
  • returning error condition as early as possible instead of executing whole code
  • Increase the readability of code

For eg.

without early return

function divide(dividend, divisor){
    var result;
    if(!isNaN(dividend) && !isNaN(divisor)){
      if(divisor !== 0){
        result = dividend/divisor
      } else {
        result = 'Divisor should not be zero'
      }
    } else {
      result = 'Input should be number'
    }
  return result;
}

Most people prefer to have an only one return statement But If we look at the code there are unnecessary else statements and the code looks complex

with early return

function divide(dividend, divisor){
    if(isNaN(dividend) || isNaN(divisor)){
      return 'Input should be number'
    }
    if(divisor == 0){
      return 'Divisor should not be zero'
    }
  
  return dividend/divisor
}

Here we have multiple return statements. But it looks clean and clear. Like we able to understand that which are the error condition and when to execute the code

As soon as we are getting the result we are returning from the function instead of executing the whole code.

Conclusion:

If there is only one condition then a simple if-else statement is fine. But If we need to deal with a number of if-else statements, then its always good to return a function as early as possible instead of making it complicated.

If you love the article follow me on twitter for more updates.