Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if..else vs if(){return} [duplicate]

Tags:

javascript

In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?

// Method 1
function (a, b) {
  if (a == b){
    // I'm just interested in
    // the stuff happening here
  } else {
    // or here
  }
return true;
}

// Method 2
function (a, b) {
  if (a == b){
    // I'm just interested in
    // the stuff happening here
    return true;
  }
  // or here
  return true;
}
like image 440
knex Avatar asked Aug 03 '11 18:08

knex


3 Answers

It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.

Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.

However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.

like image 57
Todd Moses Avatar answered Oct 22 '22 23:10

Todd Moses


I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.

like image 43
hspain Avatar answered Oct 22 '22 23:10

hspain


I would base my decision on clarity of code and readability, i.e.:

  • Choose method 1 when you need to do more stuff in the block after the if-block.
  • Choose method 2 when you only need two blocks of code, it's then clearer to read
  • Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.

Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.

like image 28
Abel Avatar answered Oct 22 '22 23:10

Abel