Possible Duplicate:
Should ‘else’ be kept or dropped in cases where it’s not needed?
When
a = 0
This:
var foo = function() {
if (a != 0) return true
return false
}
Or this:
var bar = function() {
if (a != 0) return true
else return false
}
I personally like the Syntax:
Simply because I find myself in the situation if I simply do
or
or
That it's not as clear,even though with the right comment the one liner is cool, and if I'm doing a comparison anyways there is a good chance that down the road I may think of something that needs to happen in that area anyways, I mean I'm doing an if for more than grins. Also if I find a special case that needs an Else If its just a matter of adding in the Else If portions.
If the language requires braces for if/else statements, I personally like to remove the else statement and the accompanying braces. The intention of the code will be just as clear, but the code will be less indented, which (usually) improves readability.
As others mentioned, the compiler will optimize the else statement. But if you're dealing with an interpreted language, the else statement has to be interpreted. In that case removing it will result in a minor (very minor) performance increase.
In this case just return the expression result directly.
But in general I try to avoid having returns from the middle of a function. Have one return per function.
It doesn't matter. The compiler will turn out the same code either way. Check to see what convention existing code follows, and then just do the same.
Personally I don't put the "else" because it's obvious. I find that the extra "else" looks cluttered.
Of course "else" should be declared explicitly.
There are several reasons why 'else' should be declared explicitly :
I won't sacrifice readability for some "cool" programming style. But, i will understand if you're facing bandwith-oriented problem like minifying javascript.
On the conceptual reason above, it - of course - depends on your function specification. For some function it makes sense to use such code. For example "Function assumes the visitor is not registered, he is only registered only if bla-bla-bla".
But for another problem like "If a number is divisible by two then it is even otherwise odd", you should write it explicitly so that a reader (perhaps not a programmer) will not be confused when reading your code. Since the reader (maybe a mathematician) only knows such invariant and he/she only knows a little about programming language.