Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}; 
like image 771
Nobody Avatar asked Aug 20 '15 04:08

Nobody


People also ask

What is a reason to not use an ES6 arrow function?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is an ES6 arrow function?

Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions. For example, This function // function expression let x = function(x, y) { return x * y; }

How do you pass parameters in arrow function?

The arrow function can be shortened: when it has one parameter you can omit the parentheses param => { ... } , and when it has one statement you can omit the curly braces param => statement . this and arguments inside of an arrow function are resolved lexically, meaning that they're taken from the outer function scope.


1 Answers

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.

like image 51
Felix Kling Avatar answered Sep 23 '22 17:09

Felix Kling