Reputation: 6072
MDN defines the usage of the spread operator as acting for arrays only.
For example, a proper usage for the spread operator looks like
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]
where we have applied the spread operator on the array parts
.
But in the React docs, they use the spread operator on objects like so
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
If I actually try to do this in the console, I receive a TypeError
var a = {b:1,c:2}
console.log(...a); // TypeError
My questions are:
Upvotes: 2
Views: 1282
Reputation: 816770
If I actually try to do this in the console, I receive a TypeError
You are confusing some things here (can't blame you if they all look similar).
In your example,
console.log(...a);
the ...a
is not an application of object spread. It's sometimes referred to as spread syntax (even though this one specifically doesn't really have a name), which is standardized in ES2015. It is used in function calls as last "argument" and only works on iterables. Objects are not iterables and hence you get the error.
Object spread, which currently is a proposal, is only used in object literals:
var foo = {x: 42};
var bar = {y: 21, ...foo}; // equivalent to Object.assign({y: 21}, foo);
what is going on under the hood
The use inside JSX (<Component {...props} />
) is a again something slightly different, its a JSXSpreadAttribute, but it does desugar to object spread. If you try it out in Babel you can see what it is converted to:
var _extends = Object.assign || /* polyfill */;
React.createElement(Component, _extends({ foo: true }, props));
Upvotes: 4
Reputation: 12260
The spread operator is being standardized at the moment, and so it cannot be used with just ES2015. At this moment it is a proposal in stage 2 of the process and will presumably be in the ES2017 spec.
https://github.com/sebmarkbage/ecmascript-rest-spread
It already can be leveraged by using some additional babel plugins when transpiling to ES5. This is what is used in the samples you mentioned.
http://babeljs.io/docs/plugins/transform-object-rest-spread/
http://babeljs.io/docs/plugins/preset-stage-2/
Upvotes: 3