Why is `throw` invalid in an ES6 arrow function?

风流意气都作罢 提交于 2019-11-27 14:57:30

If you don't use a block ({}) as body of an arrow function, the body must be an expression:

ArrowFunction:
    ArrowParameters[no LineTerminator here] => ConciseBody

ConciseBody:
    [lookahead ≠ { ] AssignmentExpression
    { FunctionBody }

But throw is a statement, not an expression.


In theory

() => throw x;

is equivalent to

() => { return throw x; }

which would not be valid either.

You can't return throw this is effectively what you're trying to do:

function(){
  return throw 42;
}

If you omit the braces in an arrow function, you create an implicit return, which is equivalent to creating an explicit return with the braces, like so: () => { return throw 42 };

However, you can only return expressions, not statements. And throw is a statement.

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