Why does a boolean or operator (||) with an empty arrow function (() => {}) raise a SyntaxError?

In my code, I have something that boils down to the following:

var x = y || ()=>{}; 

(In case you are interested, I call x() later, and y may be defined as a function or it may not be, so I don’t want a TypeError to be thrown if it is not.)

For some reason this causes

SyntaxError: Unexpected token)

Why? I learned that

 var x = y || (()=>{}); 

works fine but

 y || ()=>{} 

does not work. Is this indicated, or a bug in V8 or Chrome? (I tested this only in the latest version of Chrome stable.)

+3
javascript arrow-functions
source share
3 answers

This is normal. Unlike the function expression, which is PrimaryExpression , like other literals and identifiers, the arrow function is AssignmentExpression and can only appear inside a group, comma, assignment, conditional (triple), and yield expression. Any other operator than those will lead to ambiguity.

For example, if you expect y || ()=>z y || ()=>z will work, then it should also be expected that ()=>z || y ()=>z || y will work (assuming a symmetric priority). This, however, clearly confronts our expectation that we can use any operators inside the short bodies of arrow functions. Therefore, this is a syntax error and requires that the explicit grouping work and remain maintainable.

+4
source share

This is not a bug in the JavaScript engine. This behavior is documented.

Although an arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator priority over regular functions.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Parsing_order

+2
source share

try var x =( y || (()=>{}));

0
source share

All Articles