Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we have to wrap throw with brackets in es6 arrow functions [duplicate]

I want to ask if someones knows the reason why

const fun = msg => throw new Error( msg ); is invalid JS while

const fun = msg => { throw new Error( msg ); } is valid

Since

const fun = msg => new Error( t ); is valid

Someone (I would) would expect also the case with throw to be valid JS.

Is there any reason behind this choice? e.g. does it makes it difficult to the interpreter or something?

like image 928
Avraam Mavridis Avatar asked Jan 06 '23 08:01

Avraam Mavridis


1 Answers

Arrow functions are defined like this:

ArrowFunction[In, Yield] :
    ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]ConciseBody[In] :
    [lookahead ≠ { ] AssignmentExpression[?In]
    { FunctionBody }

And throw is an statement:

ThrowStatement[Yield] :
    throw [no LineTerminator here] Expression[In, ?Yield] ;

Then the first ConciseBody body syntax won't work because AssignmentExpression doesn't include statements:

AssignmentExpression :
    YieldExpression
    ArrowFunction
    LeftHandSideExpression = AssignmentExpression
    LeftHandSideExpression AssignmentOperator AssignmentExpression
    BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
    BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
    BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression

If you use braces, then the inner part of ConciseBody will be a FunctionBody, which is a list of statements. So a ThrowStatement is allowed.

like image 95
Oriol Avatar answered Jan 26 '23 21:01

Oriol