1

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 ?

3
  • 2
    you check against a string. is it right? Commented May 12, 2019 at 17:23
  • Why is the value of download a string? Why are you using == and not === on index? Commented May 12, 2019 at 17:23
  • it's actually a string, i just named it index of an object given which is the name of it Commented May 12, 2019 at 17:25

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

1 Comment

oh it worked for me and thank you for the detailed explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.