↩️Clean Coding Tip: Early Return Principle

Shameel Uddin - Nov 9 '23 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player