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>If you do a lot of Node.js, you’ve probably seen this flow in Express middleware:</p>
<pre>
// JavaScript
function authMiddleware(req, res, next) {
const authToken = req.headers.authorization;
if (!authToken) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (authToken !== 'secret-token') {
return res.status(401).json({ error: 'Invalid token' });
}
if (req.query.admin === 'true') {
req.isAdmin = true;
}
next();
}</pre>
<p>It’s much better than this, right? :</p>
<pre>
// JavaScript
function authMiddleware(req, res, next) => {
const authToken = req.headers.authorization;
if (authToken) {
if (authToken === 'secret-token') {
if (req.query.admin === 'true') {
req.isAdmin = true;
}
return next();
} else {
return res.status(401).json({ error: 'Invalid token' });
}
} else {
return res.status(401).json({ error: 'Unauthorized' });
}
};</pre>
<p>You never go beyond one level of nesting. We can avoid the mess that we see in callback hell.</p>
<h1>How to convert nested ifs to guard clauses</h1>
<p>The logic for this for doing this is simple:</p>
<h1>1. Find the innermost/success if</h1>
<p>Here we can clearly see it’s the <code>cond3</code> if. After this, <code>if</code> we don't do any more checks and take the action we've always wanted to take.</p>
<p><a href="https://medium.com/coding-beauty/stop-using-nested-ifs-ed30e5ea5086">Visit Now</a></p>