Search code examples
javascriptnode.jsif-statementoperator-keywordexpression-evaluation

Short circuit evaluation in JavaScript - SyntaxError: Unexpected token 'return'


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)?


Solution

  • 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.