Paulo Santos
Paulo Santos

Reputation: 75

Why are parentheses needed in this expression?

In the following code snippet:

// Error code:
(y,...x) => {...x,y};
// output = "SyntaxError: Unexpected token ..."

// Expected result:
(y,...x) => ({...x,y});

I don't quite understand why the "()" are needed to surround the object literal. I suspect it is due to the spread operator, as when i remove it I no longer need the parentheses. Surely i'm missing something obvious here?

Upvotes: 1

Views: 94

Answers (2)

jo_va
jo_va

Reputation: 13983

The parentheses are needed to implicitly return an object literal from your arrow function.

Without parentheses, the braces would be considered as the body of your function, so they help force the parser to treat the object literal as an expression so that it's not treated as a block statement.

(y,...x) => ({ ...x, y });

is equivalent to:

(y,...x) => { return { ...x, y }; };

Upvotes: 2

SLaks
SLaks

Reputation: 888185

{x,y} is a block which evaluates x and y, does nothing, and returns undefined.

Adding ... turns that into a syntax error, since that isn't a valid statement.

The parentheses force it to be parsed as an expression.

Upvotes: 3

Related Questions