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;
}
                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.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With