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

I'm just looking for a reason as to why this is invalid:

() => throw 42;

I know I can get around it via:

() => {throw 42};

Answers:

Answer

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.

Answer

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

function(){
  return throw 42;
}
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.