single return vs multiple returns
See original GitHub issueI 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;
}
Issue Analytics
- State:
- Created 8 years ago
- Comments:22 (2 by maintainers)
Top Results From Across the Web
Single return vs Multiple returns - JDriven Blog
If a function has multiple points of exit where no more computing should be done, multiple returns has the advantage in my opinion...
Read more >Should a function have only one return statement?
Structured programming says you should only ever have one return statement per function. This is to limit the complexity. Many ...
Read more >The Single Return Law | anthonysteele.github.io
One return is more readable than two in the sense that one statement is easier to read than two, but I'm in favour...
Read more >Where did the notion of "one return only" come from?
Multiple returns introduce implicit paths in the code to just past the end of the function (or method) that are ...
Read more >Religious War #48293: Single Vs. Multiple Returns
Personally, I don't mind multiple returns. It often makes code more readable, less if-nesting, etc. But it has almost become a war here...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub 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, singlereturn
with mutable result variable requires additionalelse
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.