DEV Community

Discussion on: Why is it you can execute a function on the right side of an AND && operator in JavaScript

Collapse
 
peerreynders profile image
peerreynders • Edited

Being an operator it's part of an expression:

"An expression is any valid unit of code that resolves to a value."

Logical AND and Logical OR are binary operators, i.e. they require two operands. Those operands can be expressions because an expression resolves to a value. A function invocation is considered an expression because it will resolve to a value after the call (even if it is just undefined).

On top of this && and || use short circuit evaluation:

  • Given lhs && rhs the rhs expression will never be evaluated if lhs evaluates to a falsy value. That falsy value is what the && operator evaluates to.
  • Similarly with lhs || rhs the rhs expression will never be evaluated if lhs evaluates to a truthy value. That truthy value is what the || operator evaluates to.

So somethingFalsy && fn(value) won't execute fn(value) while somethingTruthy && fn(value) will execute fn(value). In the former case somethingFalsy will be the resulting value (ignored if not used) while whatever fn(value) returns is the result for the latter.