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&rsquo;s valid before finally doing something useful with it.</p> <p>Don&rsquo;t do this! :</p> <pre> // JavaScript function sendMoney(account, amount) { if (account.balance &gt; amount) { if (amount &gt; 0) { if (account.sender === &#39;user-token&#39;) { account.balance -= amount; console.log(&#39;Transfer completed&#39;); } else { console.log(&#39;Forbidden user&#39;); } } else { console.log(&#39;Invalid transfer amount&#39;); } } else { console.log(&#39;Insufficient funds&#39;); } }</pre> <p>There&rsquo;s a better way:</p> <pre> // JavaScript function sendMoney(account, amount) { if (account.balance &lt; amount) { console.log(&#39;Insufficient funds&#39;); return; } if (amount &lt;= 0) { console.log(&#39;Invalid transfer amount&#39;); return; } if (account.sender !== &#39;user-token&#39;) { console.log(&#39;Forbidden user&#39;); return; } account.balance -= amount; console.log(&#39;Transfer completed&#39;); }</pre> <p>See how much cleaner it is? Instead of nesting ifs, we have multiple if statements that do a check and&nbsp;<code>return</code>&nbsp;immediately if the condition wasn&#39;t met. In this pattern, we can call each of the&nbsp;<code>if</code>&nbsp;statements a&nbsp;<strong>guard</strong>&nbsp;<strong>clause</strong>.</p> <p>If you do a lot of Node.js, you&rsquo;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: &#39;Unauthorized&#39; }); } if (authToken !== &#39;secret-token&#39;) { return res.status(401).json({ error: &#39;Invalid token&#39; }); } if (req.query.admin === &#39;true&#39;) { req.isAdmin = true; } next(); }</pre> <p>It&rsquo;s much better than this, right? :</p> <pre> // JavaScript function authMiddleware(req, res, next) =&gt; { const authToken = req.headers.authorization; if (authToken) { if (authToken === &#39;secret-token&#39;) { if (req.query.admin === &#39;true&#39;) { req.isAdmin = true; } return next(); } else { return res.status(401).json({ error: &#39;Invalid token&#39; }); } } else { return res.status(401).json({ error: &#39;Unauthorized&#39; }); } };</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&rsquo;s the&nbsp;<code>cond3</code>&nbsp;if. After this,&nbsp;<code>if</code>&nbsp;we don&#39;t do any more checks and take the action we&#39;ve always wanted to take.</p> <p><a href="https://medium.com/coding-beauty/stop-using-nested-ifs-ed30e5ea5086">Visit Now</a></p>