JavaScript early returns versus nested if statements

Improve your JavaScript code with the right form of conditional logic for each code block. Learn about early returns versus nested if statements.
August 20, 2023JavaScript
5 min read

Conditional logic in JavaScript can be written in different ways. We can use a switch statement, early returns, or nested if statements.

Nested if statements can help with organization while early returns can be easier to read. One is not better than the other. It's all about choosing the one that makes the code more readable and maintainable over time.

Early returns

Rather than nesting multiple if statements, early returns allow us to break out of a function as soon as a certain condition is met. Early returns tend to be more elegant since they make the programmer's intent clearer.

Examples of early returns

Let's define a function that calculates a discount percentage based on the price of a product.

Let's say that we want all products to be 10 percent off. However, if the price happens to be less than 20 dollars, we should not apply a discount. We'll use an early return to make sure no discount is returned.

function calculateDiscount(price) {
  if (price < 20) {
    return 0; // Early return
  }

  return 0.1; // (10% off)
}

We can also use multiple early returns to return a specific discount if a certain spending threshold is reached. If the price is between 20 and 100, we'll return a 10 percent discount. If the price is between 101 and 200, we'll return a 20 percent discount. For prices above 200, we'll return a 30 percent discount.

function calculateDiscount(price) {
  if (price < 20) {
    return 0; // Early return
  }

  if (price <= 100) {
    return 0.1; // Early return (10% off)
  }

  if (points <= 200) {
    return 0.2; // Early return (20% off)
  }

  return 0.3; // (30% off)
}

Advantages of early returns

  • Readability: Early returns promote a flatter code structure with less nesting. This results in less tracing of nested blocks by readers of your code. They can understand the logic a lot quicker.

  • Easier debugging: Identifying which condition triggered an unexpected behavior is easier with early returns because you don't have to keep track of multiple indentation levels for each condition.

  • Improved performance: Early returns can improve performance by breaking out of a function early, reducing unnecessary computations. When a condition is met, the function execution ends. This can potentially saving processing time.

Nested if statements

Nested if statements handle a sequence of conditions. They can be nested several levels deep. They are helpful for handling code with complex conditions. However, they can result in code that is harder to read and understand.

Advantages of nested if statements

  • Organizes complex logic: When code requires lots of branching for multiple conditions, nested if statements provide a more organized structure to manage all possible cases.

  • Greater flexibility: The logical flow of code can't always be simplified with early returns. Sometimes we need every single condition to perform a certain action. Nested if statements are flexible enough to be used for all cases.

Example of nested if statements

Let's rewrite the previous calculateDiscount function using nested if statements. Let's also add a second function parameter for the user's membershipType which will determine the type of discount that they'll get, along with the price that they spend.

function calculateDiscount(price, membershipType) {
  if (membershipType === 'Gold') {
    if (price > 100) {
      return price * 0.2; // (20% off)
    } else {
      return price * 0.1; // (10% off)
    }
  } else if (membershipType === 'Silver') {
    if (price > 100) {
      return price * 0.1; // (10% off)
    } else {
      return price * 0.05; // (5% off)
    }
  } else {
    return 0;
  }
}

Nested if statements work better than early returns in this example because we have multiple branches of logic to handle multiple conditions.

Early return in a React event handler

Consider the following example of a React Button component that triggers an onClick event which calls a someFunction event handler. A value is passed to the event handler. The value can be a string, null, or undefined.

<Button onClick={() => someFunction(value)}>Save</Button>

Inside the someFunction event handler, we would like to check if the value is defined and if the value is unique among a list of items.

Let's write this logic in the someFunction event handler using nested if statements.

const someFunction = (value?: string) => {
  if (value) {
    const isUnique = !items.some((item) => item === value);
    if (isUnique) {
      // do something with the value
    }
  }
};

We can make this logic slightly easier to read by returning early if the value is falsy or if the value is not unique among a list of items.

const someFunction = (value?: string) => {
  if (!value) return;

  const isUnique = !items.some((item) => item === value);
  if (!isUnique) return;

  // do something with the value
};

Conclusion

If your conditions are simple, early returns are cleaner and easier to read. For more complex conditional logic, nested if statements will do a better job at organizing that logic.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.