0

I would like to use short circuit evaluation syntax (with && operator) as described by example in the article:

Say, I have this situation:

function externalFunction() {

    id == ...
    text == ...

    // OK: Standard if syntax is fine

    if ( aFunction(id, text) ) return

    // KO: Short circuit evaluation generate a RUN-TIME ERROR: 
    // SyntaxError: Unexpected token 'return'
    // anotherFunction(id, text) && return
    //                              ^^^^^^

    anotherFunction(id, text) && return


}

Why I have the error? Maybe I can't use a single statement with language keyword (return)?

Giorgio Robino
  • 2,148
  • 6
  • 38
  • 59

1 Answers1

6

The right hand side of && needs to be an expression. You're trying to put a statement there.

The && has to evaluate as something but return x doesn't give you a value. It exits the function and passes its RHS to the calling function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thanks, true. I was looking to find an "elegant"/short way to evaluate a list of functions/conditions, that have to return from the external function in case they return true. – Giorgio Robino Feb 18 '20 at 14:05
  • 1
    Use an `if` statement. It is clear and elegant. Extreme brevity is not a virtue. – Quentin Feb 18 '20 at 14:11