DEV Community

Shameel Uddin
Shameel Uddin

Posted on

↩️Clean Coding Tip: Early Return Principle

Have you ever looked at a piece of code and got confused a bit due to many nested if statements, one inside another?

Clean code is all about making your code

  • Readable
  • Maintainable
  • Easy to understand.

In this blog, we'll discuss a simple coding tip to enhance the clarity of your JavaScript code: Avoiding Nested IF with Early Return Principle.
We'll break down the concept of clean code and provide coding examples in simple JavaScript.

What is Clean Code?

Clean code is like a well-organized book. It's easy to read, easy to maintain, and easy to understand. When you write clean code, it's like telling a clear and concise story with your program. You want your code to be a joy to work with, not a puzzle that needs solving.

The Problem with Nested IF Statements

When you nest IF statements, you increase the complexity of your code. It's like stacking multiple puzzles on top of each other, making it harder to figure out the logic. Nested IF statements can quickly lead to confusion and errors, especially in larger codebases.

Look at this coding example:

function calculatePrice(item) {
  if (item.type === 'book') {
    if (item.pages > 500) {
      return item.price * 0.9;
    } else {
      return item.price * 0.95;
    }
  } else {
    return item.price;
  }
}
Enter fullscreen mode Exit fullscreen mode

Solution With Early Return Principle

Writing clean code is a skill that can be learned and improved with practice. One of the fundamental principles of clean code is the "early return" principle.

This principle suggests that you should exit a function as soon as the necessary conditions are met, rather than creating layers of nested IF statements.

Above code can be simplified as:

function calculatePrice(item) {
  if (item.type !== 'book') {
    return item.price;
  }

  if (item.pages > 500) {
    return item.price * 0.9;
  }

  return item.price * 0.95;
}

Enter fullscreen mode Exit fullscreen mode

💡 The idea is to have as simplified if statements as possible and return if the conditions are met; instead of nesting them down.

Conclusion

Clean code is an essential aspect of software development. By following the early return principle and merging nested IF statements into one condition, you can greatly improve the readability of your JavaScript code.

Keep practicing this skill, and your code will become a joy to work with, not a source of confusion.

Happy coding! 🎉💻✨

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (5)

Collapse
 
efpage profile image
Eckehard • Edited

Sorry, but your initial example is a bit confused. You do not need an else after return. This is the same code without the superfluous else. And you used early return already, but ok, it is not very readable:

function calculatePrice(item) {
    if (item.type === 'book') {
        if (item.pages > 500) 
            return item.price * 0.9 
        return item.price * 0.95;   
    } 
    return item.price;  
}
Enter fullscreen mode Exit fullscreen mode

Possibly, you meant something like this which is really a mess:

function calculatePrice(item) {
  let res
  if (item.type === 'book') {
    if (item.pages > 500) {
      res = item.price * 0.9;
    } else {
      res =  item.price * 0.95;
    }
  } else {
    res =  item.price;
  }
  return res
}
Enter fullscreen mode Exit fullscreen mode

Even that code can be made a bit better with some small chanages and intuitive formatting:

function calculatePrice(item) {
    let res =  item.price  // use a default value

    if (item.type === 'book') {
        if (item.pages > 500) 
            res = item.price * 0.9  
        else 
            res = item.price * 0.95 
    }
    return res
}
Enter fullscreen mode Exit fullscreen mode

But finally there are always differnt ways to solve a task. Sometimes you might need to try different options. As you just return a single value, an arrow function and the ternary operator could also be an option:

const calculatePrice = (item) =>
    item.type !== 'book' ? item.price :
        item.pages > 500 ? 
            item.price * 0.9 : 
            item.price * 0.95;

console.log(calculatePrice({ type: "book", pages: 900, price: 100 }))
Enter fullscreen mode Exit fullscreen mode

Maybe you use destructuring to make things more readable

const calculatePrice = (item) => {
    const { type, price, pages } = item
    return type !== 'book' ? price :
        pages > 500 ?
            price * 0.9 :
            price * 0.95;
}

console.log(calculatePrice({ type: "book", pages: 900, price: 100 }))
Enter fullscreen mode Exit fullscreen mode

Ok, nested ternaries are not too nice. Maybe we could split the task somehow to make it more expressive?

const bookPrice = (book) => 
     (book.pages > 500) ?  book.price * 0.9  :  book.price * 0.95

const calculatePrice = (item) =>
    (item.type == 'book') ? bookPrice(item) : item.price  
Enter fullscreen mode Exit fullscreen mode
Collapse
 
johannesvollmer profile image
Johannes Vollmer • Edited

If you want to make code readable, you want if-else instead of early returns. Back in the old languages, they only hat goto, which obscures the control flow. Then they invented if and else, and suddenly it was very easy to read control flow. They call it "structured programming", and I recommend the Talk of Kevlin Henney on it.

Early returns are like goto. Don't blindly use it. If your code is too nested, you should have split it into multiple functions instead of returning early. Keep top-level if and else.

Collapse
 
wraith profile image
Jake Lundberg

Great advice here! 😍 Nice job!

Collapse
 
shameel profile image
Shameel Uddin

thank u =)

Collapse
 
vanvikki1986 profile image
vandhuukumar

Good over talk on disscusion.