Stop using nested ifs. Do this instead
<p>A typical use case for nested ifs: you want to perform all sorts of checks on some data to make sure it’s valid before finally doing something useful with it.</p>
<p>Don’t do this! :</p>
<pre>
// JavaScript
function sendMoney(account, amount) {
if (account.balance > amount) {
if (amount > 0) {
if (account.sender === 'user-token') {
account.balance -= amount;
console.log('Transfer completed');
} else {
console.log('Forbidden user');
}
} else {
console.log('Invalid transfer amount');
}
} else {
console.log('Insufficient funds');
}
}</pre>
<p>There’s a better way:</p>
<pre>
// JavaScript
function sendMoney(account, amount) {
if (account.balance < amount) {
console.log('Insufficient funds');
return;
}
if (amount <= 0) {
console.log('Invalid transfer amount');
return;
}
if (account.sender !== 'user-token') {
console.log('Forbidden user');
return;
}
account.balance -= amount;
console.log('Transfer completed');
}</pre>
<p>See how much cleaner it is? Instead of nesting ifs, we have multiple if statements that do a check and <code>return</code> immediately if the condition wasn't met. In this pattern, we can call each of the <code>if</code> statements a <strong>guard</strong> <strong>clause</strong>.</p>
<p><a href="https://medium.com/coding-beauty/stop-using-nested-ifs-ed30e5ea5086">Read More</a></p>