Question on Short Circuit And

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"

I was very confused when I saw this. It has the same impact as doing

if n >= 5
    return "yes"
    return "no"

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?

performance is the same. it’s purely stylistic

There could be several reasons of for writing code like this. Here’s two:

  1. 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.
  2. 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:

return n >= 5 ? "yes" : "no"
1 Like