0

The follow works in node v8.11.4 and in babel transpiled JavaScript running on chrome

const myFunc = ({
  aryOfObjs,
  combinedObj = Object.assign({}, ...aryOfObjs),
}) => console.log(combinedObj);
myFunc({
  aryOfObjs: [
    { foo: 'bar'},
    { biz: 'baz' },
  ]
}); // => { foo: 'bar', biz: 'baz' }

In EMACScript 2015 is this guaranteed to work as shown above?

I know node and babel aren't 100% EMACScript 2015 complaint but I believe they both implement the object destructuring spec I can't find anything explicit on mdn that says this is supported nor on the official ECMAScript 2015 spec

rudolph9
  • 8,021
  • 9
  • 50
  • 80

1 Answers1

2

Yes, this is valid ES2015 code. aryOfObjs is a variable introduced into the function scope, and Object.assign({}, ...aryOfObjs) is an expression evaluated in that scope so it can access any of those variables. The only time this would be an error is if they were accessed out of order, like

const myFunc = ({
  combindedObj = Object.assign({}, ...aryOfObjs),
  aryOfObjs,
}) => console.log(combindedObj);

which would throw an error because aryOfObjs has not been initialized yet.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251