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
}
You should do whatever makes the code clearer.
It gets optimized at compile time anyway, so no runtime difference.
As usual, you can argue about style. My 50 cents: the first variant (no explicit else) is nicer because it's less code doing exactly the same.
Of course, in this case, you would do
return a != 0;
... but I think the question is meant to be general.
I would say it's a good practice to do so, because it would make changing the code a bit easier. For instance, let's say you wanted to print out the result. You could either change it like this:
if (a != 0) {
print "returning true"
return true
}
print "returning false"
return false
Which means adding a print twice, or else:
if (a != 0) {
retval = true
} else {
retval = false
}
print "returning ", retval
return retval
which means adding one print, but this won't work without the else.
Of course, this is a contrived example, but it shows how you should try to make your code as maintainable as possible.
As the compiler will probably reduce it to the same compiled code anyway, do what you believe to be more "beautiful".
Note that code elegance is subjective, so dogmatically clinging to one format or another is unnecessary.
if(statement)
result = true
else
result = false
return result
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