Are there any negative effects of using an implicit return statement in an arrow function with a logical AND operator &&?
Absolutely, there are a couple:
One concern is the potential maintenance issue highlighted in the question: If fn(val)
returns a falsy value, that value will be returned by the arrow function instead of val
. This can lead to confusion for anyone modifying the logic of fn
, as assumptions about its return value may not hold true elsewhere.
Another maintenance challenge arises when attempting to add additional calls or logic to the arrow function, as decoding a &&
expression can be more complex.
Subjectively, this approach may be harder to comprehend, especially when the &&
operator serves a purpose beyond simply avoiding the use of return
.
To tackle the first issue, some developers utilize (or some might say exploit) the comma operator:
const tap = fn => val => (fn(val), val);
I am not endorsing this technique, just mentioning it as a possibility. The comma operator evaluates the left-hand side, discards the result, evaluates the right-hand side, and uses that as the final output. When employing a comma expression as a concise body for an arrow function, parentheses are necessary around the expression to avoid cutoff at the comma. Essentially, the only saved typing is skipping the word return
.
Potential issues could arise with bundlers or optimizers altering the code
This would only happen if those tools had bugs. Their main purpose is to accurately interpret the code provided. Compact arrow functions fall under their purview.
However, on the topic of tools: It's generally advisable to write your code as clearly as possible. Minification efforts to condense it should be left to dedicated toolsets.