How to use arrow function with || operator

a 夏天 提交于 2019-11-27 15:36:42

It fails because that is just not valid syntax.

Use the following to make it work:

callback = callback || (() => {})

If you don't wrap it that way, it would be interpreted as if you typed the following. But that is invalid syntax.

callback = (callback || ()) => {}

To extend on the evaluation of the assignment, see the specification of the AssignmentExpression. It consist of a ConditionalExpression or an ArrowFunction (or some other expressions I will disregard). So the interpreter will try to use your code as a conditional. But the () itself is not valid in that context as an expression is expected inside that ParenthesizedExpression. As a result, it will fail. If you instead group the expression as callback || (() => {}) both sides of the LogicalOrExpressions are valid expressions.

Due to operator precedence, you have to wrap the arrow function in parentheses to make it work:

callback = callback || (() => {})

If you're planning to use the || to provide a default value for the callback parameter to a function, it's easier to just write

function myfunc(callback = () => { }) {
  callback("Hi 1252748");
}

No extra parens needed.

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