The "single var pattern" often found in Javascript suggests single points of return by insisting that all variables are declared at the top of the function body to prevent "hoisting". Thus, recording the evaluations instead of returning can prevent the need for an ELSE (which I have a strange aversion to...):
function doThis(required){
var result = false;
if(required){
//base implementation
result = doThat();
}
return result;
}
If you have sequential or optional conditions and can't break out to another function, then you can do this:
function doThis(required, opt){
var result = false,
oRequirement = 'foo';
if(required){
//base implementation
result = doThat();
if(result !== false && opt !== undefined && opt === oRequirement){
//optional implementations
result = doOptional();
} else {
//undo previous truthiness
result = false;
}
}
}
return result;
}
You could delegate consumption of variables externally, making this function effectively a "guard clause":
function vA(a){
return true;
}
function vB(c){
return true;
}
function vB(c){
return true;
}
function doThis(required, opt){
var result = false;
if(vA(required)){
//base implementation
result = doThat(required);
if(vB(result) && vC(opt)){
//optional
result = doOptional(opt);
}else{
result = false;
}
}
return result;
}
You could layer your evaluations:
function doThis(required, opt){
var result = false;
if(if(vA(required)){
//base
result = doThat(required);
}
if(if(vB(result) && vC(opt)){
//optional
result = doOptional(opt);
}
return result;
}
Ternaries can reduce size, and are very pretty, but they can be a little harder to debug, and a bit inconvenient if you need much in the way of nested evaluation steps:
function doThis(a, b, c){
var o = false;
if(valid(a)){ //assuming some sort of validation is required
if(b !== undefined && valid(b)){
o = c ? //an optional step
doMore(a) ?
new Foo(a, b) :
false :
new Bar(b, a) ;
}
}
return o;
}
Generally speaking, I need to nest IF statements if optional arguments are present. When the outcome is the result of a process within the body, then it suggests delegating or chaining into a separate method.
Having said that, I can't help but feel that there is no "right" way (although there are certainly wrong ones...), and it's this fact that makes coding a creative profession capable of a broad range of expression. I mean, who doesn't love a bit of refactoring?
else
if the previousif
is used to return. Mozilla coding guidelines require you to omit those elses. Otherwise, you may use a variabl, say,ret
which you set accordingly in the If-Else ladder, and finally returnret
in the end. I like to use switch-case particularly with this.