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
};
}
};
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;
};
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.
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