Why does the logical or operator (||) with an empty arrow function (()=>{}) cause a SyntaxError?

懵懂的女人 提交于 2019-11-26 14:53:28

问题


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

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

(In case you are wondering, I am later calling x() and y may be defined as a function or it might not, so I don't want a TypeError to be thrown if it is not.)

For some reason, this causes a

SyntaxError: Unexpected token )

Why? I found out that

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

works just fine, but

y || ()=>{}

dosen't work. Is this specced, or a bug in V8 or Chrome? (I tested this only in the latest release of Chrome stable.)


回答1:


This is normal. Unlike a function expression, which is a PrimaryExpression like other literals and identifiers, and arrow function specifically is an AssignmentExpression and can only appear inside grouping, comma, assignment, conditional (ternary) and yield expressions. Any other operator than those would lead to ambiguities.

For example, if you expect y || ()=>z to work, then also ()=>z || y should be expected to work (assuming symmetric precedence). That however clearly collides with our expectation that we can use any operators inside concise bodies of arrow functions. Therefore, it's a syntax error and requires explicit grouping to work and stay maintainable.




回答2:


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

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

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




回答3:


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



来源:https://stackoverflow.com/questions/42679078/why-does-the-logical-or-operator-with-an-empty-arrow-function-caus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!