I was reviewing some source code recently for a package I am using and saw a function essentially defined like this (dumbed down to a MWE here).
function func(n)
(n >= 5) && return "yes"
return "no"
end
I was very confused when I saw this. It has the same impact as doing
if n >= 5
return "yes"
else
return "no"
end
So why not do that? The line (n >= 5) && return "yes" is just so much less readable than the if-else statement. Perhaps it was done for performance reasons?
There could be several reasons of for writing code like this. Here’s two:
early return: It is good practice and idiomatic in many imperative languages to test for the trivial edge cases first, and use early returns in a function body. This technique lets you focus on the real problem.
no else after return: some linters issue a warning when you have an else branch after a return clause in a then branch. This is reasonable, because the else is, strictly speaking unnecessary, and increases indendation.
Note that both reasons make real sense only when the else branch is a lot more complicated. In this particular case, I’m guessing it’s just a convention/habit that was blindly followed. I personally would write this using a ternary operator: