DEV Community 👩‍💻👨‍💻

Cover image for Avoiding IF nesting ✨
Jesús Mejías Leiva for Wealize

Posted on • Updated on • Originally published at blog.susomejias.dev

Avoiding IF nesting ✨

Introduction

Today I come to share a little tip to improve the readability of our code. We will achieve this by using guard clauses which will help us avoid this IF nesting.

Examples

Bad ❌

In this example, we can see how and IF nesting appears, in this case, it is a simple example but this can get complicated, with each nesting that is added the code will become less readable and therefore less friendly and less maintainable.

const calculatePercentageHeight = (width, height) => {
  const result = (height * 100) / width;

  if (!Number.isNaN(result)){
    if (Number.isInteger(result)){
      return result
    }else{
      return result.toFixed(2)
    }
  }else{
    return 0
  }
};

// use function
calculatePercentageHeight(50,50) // result 100
calculatePercentageHeight(50,0) // result 0
Enter fullscreen mode Exit fullscreen mode

Good ✅

Using guard clauses we avoid the nesting of IF conditionals since we will "first control the error cases", and then we will continue with our logic.

const calculatePercentageHeight = (width, height) => {
  const result = (height * 100) / width;

  if (Number.isNaN(result)) return 0; // guard clause
  if (Number.isInteger(result)) return result; // guard clause

  return result.toFixed(2);
};

// use function
calculatePercentageHeight(50,50) // result 100
calculatePercentageHeight(50,0) // result 0
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using guard clauses is good practice to avoid unnecessary ramifications and therefore make your code easier and more readable. If we apply these guidelines we will make our software much more maintainable and friendly.

Thanks for reading me. 😊

thanks

Oldest comments (2)

Collapse
 
javaguirre profile image
Javier Aguirre

👏👏

Collapse
 
susomejias profile image
Jesús Mejías Leiva Author • Edited on

thanks!! 🙌

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.