1

Using this example from MDN:

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
const merge = ( ...objects ) => ( { ...objects } );

let mergedObj1 = merge (obj1, obj2);
console.log(mergedObj1); // { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }

I know merge is an arrow function doing an implicit return (of first expression?). I want to know why we have to wrap ...objects in a grouping operator/paranthesis.

1 Answers1

1

Let us consider the function definition: const merge = ( ...objects ) => ( { ...objects } );. Here the parameter ...objects is using the spread operator to create an array of all the arguments passed to this function. That makes it possible to pass any arbitrary number of parameters and it will create a corresponding array. If you look at what is produced it may look like this:

[ { foo: 'bar', x: 42 }, { foo: 'baz', y: 13 } ]

Within the body of the function you are now spreading the array itself. Wrapping that in the {} creates the object. But, since you are using the implicit return (without the return statement) there might be some ambiguity between the {} for the object and the {} that normally wraps the body of the function. Hence the () wrapping the whole statement.

That function could have been written like this:

const merge = (...objects) => {
  return { ...objects };
}
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192