Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 307
neaumusic Avatar asked Jan 24 '26 05:01

neaumusic


1 Answers

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) );
like image 173
Oriol Avatar answered Jan 26 '26 19:01

Oriol