Have you ever seen a piece of code looking like this?
function canDrink(person) { if (person?.age !== null) { if (person.age < 18) { console.log('No'); } else if (person.age < 21) { console.log('Not in the US'); } else { console.log('Yup'); } } else { console.log('You are not a person'); } } const john = { p: 22 }; canDrink(john); // 'Yup'
Although it is very common, we can agree that it is not really readable and hardly maintainable. This is of course a simple example, but we can sometimes see hundreds of lines with nested if, and we surely don't want to do anything with it.
Instead, we can try to simplify the code.
Let's take the example above.
We are first going to deal with the main if / else statement, testing if person.age is null instead of not null, then stop the execution right after our console.log. As you can see, we are now able to remove the else.
function canDrink(person) { if (person?.age === null) { console.log('You are not a person'); return; // Stop the execution here. } if (person.age < 18) { console.log('No'); } else if (person.age < 21) { console.log('Not in the US'); } else { console.log('Yup'); } }
Let's do the same with the rest of the method, which gives:
function canDrink(person) { if (person?.age === null) { console.log('You are not a person'); return; } if (person.age < 18) { console.log('No'); return; } if (person.age < 21) { console.log('Not in the US'); return; } console.log('Yup'); }
It is already much more readable. However, it is not really satisfying either, we can do better by splitting our code:
function canDrink(person) { if (person?.age === null) { console.log('You are not a person'); return; } const response = canDrinkResponse(person.age); console.log(response); } function canDrinkResponse(age) { if (age < 18) return 'No'; if (age < 21) return 'Not in the US'; return 'Yup'; }
Tada 👏
This is now really easy to read, debug and maintain!
You can try to apply this approach in your code to make it cleaner, simply avoiding 'else' statements.