Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Don't abuse `return`

View to_return_or_not_return.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// BAD: `return` shouldn't be used to control flow/execution
function loadProductData(query) {
if ($('body').hasClass('busy'))
return;
 
$.ajax( /*...*/ );
}
 
// GREAT SUCCESS: Just do this instead (OMG duh!)
function loadProductData(query) {
if (!$('body').hasClass('busy')) {
$.ajax( /*...*/ );
}
}
 
// BAD: Always return if you're going to return
function performScientificMaths(x, y) {
if (x + y > 0) {
return x + y;
}
}
 
// GREATE SUCCESS: Never a null (I mean, undefined) moment
function performScientificMaths(x, y) {
if (x + y > 0) {
return x + y;
} else {
return null;
}
}

I disagree.

function A(q) {
    if(q){
        // 100 lines of code
    }
}

is ugly. I rather have:

function A(q) {
    if(!q){
        return;
    }

    // 100 lines of code
}

I agree that the following is nice

function performScientificMaths(x, y) {
    if (x + y > 0) {
        return x + y;
    } else {
        return null;
    }
}

but why not skip the else all together;

function performScientificMaths(x, y) {
    if (x + y > 0) {
        return x + y;
    }

    return null;
}
Owner

Agreed that the else should be omitted.

With the first examples, however, I do dislike return being used to control execution. I know it's something done quite often, but I get annoyed when I'm tracing through code to nail down where things are going wrong, only to find a return plopped right in the middle of a function caused things to halt. I know it's certainly uglier looking.

Maybe I'm being nitpicky.

Owner

And I guess in the, albeit rare, case a function is refactored to start actually returning useful values, you're not unexpectedly returning undefined.

Am I grasping at straws yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.