Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint error: "unnecessary else after disruption"

I am wondering how I can re-write this function to resolve the JSLint error "unnecessary else after disruption". I understand the basics of this error, and have already rewritten functions of a model like

 myFunction.doThing = function () {
   if (user.likesCats) {
     return patCat;
   }
   else (user.likesDogs {
     return patDog;
   }
 };

to be like this instead:

 myFunction.doThing = function () {
   if (user.likesCats) {
     return patCat;
   }
   return patDog;
 }; 

But I am unsure how to fix the if, else if, else construction in this function so that it conforms to JSLint's "do not continue with unnecessary else's after a break" rule:

myFunction.getRange = function () {
  if (this.settings.allowedValues) {
    return {
      min: Min,
      max: Max
    };
  } else if (this.settings.range) {
    return {
      min: range[0],
      max: range[1]
    };
  } else {
    return {
      min: 0,
      max: 1
    };
  }
};
like image 593
Ila Avatar asked Oct 14 '13 13:10

Ila


2 Answers

Wouldn't you just set a variable instead of returning it

myFunction.getRange = function () {
    var range;
    if (this.settings.allowedValues) {
        range = {
            "min": Min,
            "max": Max
        };
    } else if (this.settings.range) {
        range = {
            "min": range[0],
            "max": range[1]
        };
    } else {
        range = {
            "min": 0,
            "max": 1
        };
    }
    return range;
};
like image 155
epascarello Avatar answered Oct 18 '22 10:10

epascarello


There are basically two approaches to this: Single Exit Point vs. Early Exit. I personally prefer the latter:

myFunction.getRange = function () {

  if (this.settings.allowedValues) {
    return {
      min: Min,
      max: Max
    };
  } 

  if (this.settings.range) {
    return {
      min: range[0],
      max: range[1]
    };
  }

  return {
    min: 0,
    max: 1
  };

};

In this case it doesn't matter much, but real-life code with early exits (return, break etc) is easier to read and maintain than "single exit" one with many else branches and temp variables.

like image 43
georg Avatar answered Oct 18 '22 12:10

georg