gtap-dev / javascript

JavaScript Style Guide
MIT License
0 stars 0 forks source link

Else after return #30

Open mjomble opened 2 months ago

mjomble commented 2 months ago

This rule disallows wrapping the last return in an else:

// bad
function foo() {
  if (x) {
    return x;
  } else {
    return y;
  }
}

// good
function foo() {
  if (x) {
    return x;
  }

  return y;
}

I agree with this rule in cases where return y is the primary path and return x is a secondary path, for example:

if (error) {
    return false; // should happen rarely
}

return true; // most of the time we get here

But there are also cases where the paths are more equal, for example:

if (isCompany) {
    return 'Ettevõte';
}

return 'Eraisik';

This code makes it look like we expect "Eraisik" in most cases and that "Ettevõte" is a less common exception.

In cases like this, it seems to me like using if-else would more clearly express that we're choosing between two more-or-less equal code branches:

if (isCompany) {
    return 'Ettevõte';
} else {
    return 'Eraisik';
}

Should we relax this rule?