DEV Community

Cover image for Don’t ever use if-else. Use this instead
Tymek Zapała
Tymek Zapała

Posted on

Don’t ever use if-else. Use this instead

Let’s talk about a coding trick that makes your code easier to read and keeps things organized: early returns.

Lots of coders rely on if-else statements to check different conditions, but stacking them up can get messy. Instead, early returns let us handle all the error cases up front, so we can save the ideal scenario for the end of the function.

Example

Here’s a function that checks if a user can get a discount:

function getDiscountMessage(user) {
  if (user.isActive) {
    if (user.hasDiscount) {
      return `Discount applied for ${user.name}!`;
    } else {
      return `${user.name} does not qualify for a discount.`;
    }
  } else {
    return `User ${user.name} is inactive.`;
  }
}
Enter fullscreen mode Exit fullscreen mode

This code is filled with nested if-else statements. 🤮

Instead, we can cover the error cases first with early returns and then focus on the "perfect scenario" at the end:

function getDiscountMessage(user) {
  if (!user.isActive) {
    return `User ${user.name} is inactive.`;
  }

  if (!user.hasDiscount) {
    return `${user.name} does not qualify for a discount.`;
  }

  // Perfect scenario: user is active and qualifies for a discount
  return `Discount applied for ${user.name}!`;
}
Enter fullscreen mode Exit fullscreen mode

Each error condition is handled in a single line right at the start. This keeps our code neat and straightforward, without all the if-else blocks of different nesting levels to follow.

So next time, skip the if-else and give early returns a try. 😎

Top comments (3)

Collapse
 
wizard798 profile image
Wizard

Nice tip for more cleaner code, I always use this guard clause in my code

Collapse
 
grantdotdev profile image
Grant Riordan

Good tip for beginners. 🙌 if you’re looking for the term to explain what you’re doing here. It’s called a “Guard clause” as guards your code and short circuits it (returning early).

Collapse
 
tymzap profile image
Tymek Zapała

Cool tip Grant, thank you!