javascript: single return vs multiple returns

I see some examples of multiple returns but don’t see any guidelines defined that say it explicitly. Is there a preference between a single return where a variable is assigned the output value vs just having multiple return statements?

function isGood(battery) {
  if (battery.charge) {
    return true;
  }

  if (battery.cycles < 10) {
    return true;
  }

  return false;
}

vs.

function isGood(battery) {
  let out = false;
  if (battery.charge) {
    out = true;
  }

  if (battery.cycles < 10) {
    out = true;
  }

  return out;
}

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Comments: 22 (2 by maintainers)

Most upvoted comments

From my POV, multiple returns are much easier to read. At first, syntax highlight will help you to subconsciously find return points in your function. With mutable variable you’ll find one return statement and then you’ll need to investigate step by step all points of mutation in the function. Also, single return with mutable result variable requires additional else statements since you don’t need the code after result computation to be invoked.

Awesome @ljharb I went for the undefined option, everything worked ok. I’m trying to convince my colleagues about the _ too.

They auto Join, i think is the right term. But Im quite sure that its not enough to make them not Monads. They still form a Kleisli Catogory, which don’t need to include a value of it self.

Btw, thanks for a Python link, that was refreshing and nostalgic.

I’ll try to make examples with out any Category Theory term and se how that works out. Thanks for the insight.