brxnzaz
brxnzaz

Reputation: 491

Refactoring repeated if statement within if else block

I have this if blocks where i have to test within on the same thing in both blocks :

   if (download !== 'true') {
     if(index == undefined){
       res.json(req.doc);
     }else{
       res.json(index)
     }
   } else {
     if(index == undefined){
       exports.download(res, req.doc);
     }else{
       res.json(index)
     }
   } 

Is there a way to refactor it in a way in which i wouldn't repeat the same thing ?

Upvotes: 1

Views: 104

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Since you do the same thing in both branches when index == undefined is false, just do that test first and invert it:

if (index != undefined) {
  res.json(index);
} else if (download !== 'true') {
  res.json(req.doc);
} else {
  exports.download(res, req.doc);
}

Side notes:

  • == undefined and != undefined will treat undefined and null the same way. If you don't want your conditions to treat null like undefined, use === and !==.
  • It's slightly odd that download is a string, although of course that does happen sometimes. If download is actually a boolean, then !== 'true' will always be true (because no boolean is ever strictly equal to a string). If it's a boolean, use if (download) or if (!download) rather than === true or !== true. If it is a string, beware of whitespace at the beginning or end and capitalization (' true' !== 'true' is true because of the space; 'True' !== 'true' is true because of the capital T). FWIW.

Upvotes: 6

Related Questions