Home  >  Article  >  Web Front-end  >  Don’t ever use if-else. Use this instead

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 12:56:02871browse

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.`;
  }
}

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}!`;
}

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. ?

The above is the detailed content of Don’t ever use if-else. Use this instead. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn