0

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?

  • 2
    The curly braces in this case are treated as the function body parentheses - i.e. `function (y, ...x) { ...x, y }`, which is invalid syntax. – Al.G. Apr 16 '19 at 15:36

2 Answers2

2

{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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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 }; };
jo_va
  • 13,504
  • 3
  • 23
  • 47