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

徘徊边缘 提交于 2019-11-27 09:45:34

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.

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

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

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