Search code examples
javascriptecmascript-6short-circuitingarrow-functions

How to know if comma separates params or is part of arrow function?


I've been messing around with using the comma in short-circuit operations:

let component = { on: (p1, p2, p3) => console.log(p1, p2, p3) };
    component.on('something', () => console.log('what do'), '???');

It seems ambiguous whether '???' is a parameter or not

Is there some sort of rule about this?

Thanks!


The order of operations doesn't seem to help, since it doesn't describe params


Solution

  • The specification defines the precedence of the operators, that's how you can know.

    12.16 - Comma Operator ( , )

    Expression[In, Yield]:
        AssignmentExpression[?In, ?Yield]
        Expression[?In, ?Yield] , AssignmentExpression[?In, ?Yield]

    14.2 - Arrow Function Definitions

    ConciseBody[In]:
        [lookahead ≠ {]AssignmentExpression[?In]
        {FunctionBody}

    The concise body of an arrow function must be an AssignmentExpression, which can't directly contain commas. But the comma operator can separate different AssignmentExpressions.

    If you want to make it clear what you are doing, add parentheses:

    console.log( (() => 2), 3 );
    console.log( (() => 2, 3) );
    console.log( () => (2, 3) );