Reputation: 322
Spreading any "empty" value in an object is valid (does not throw an error but instead becomes a kind of no-op):
{
...undefined,
...null,
...false,
...true,
...'',
...{},
...[],
...Symbol(),
...() => {},
} // evaluates to {}
But doing the same in an array throws an error for all the above values except ''
and []
. The error message says that the values that don't work are not iterable, however, they clearly are iterable in the sense that they can be spread into an object. Granted, it intuitively makes sense that strings, arrays, and objects can be converted to entries/key-value pairs when being spread into an object and converted to values when spread into an array, but even so, why would the entries of all those values be iterable but the values not be? If the entries are iterable, shouldn't the values be as well? Is this just a quirk of different JavaScript engines? What's going on here?
Upvotes: 2
Views: 382
Reputation: 18525
In object literals the spread operator
copies own enumerable properties from a provided object onto a new object. So in your examples none of the provided "entities" to the spread operator have any enumerable properties.
With arrays the spread syntax is only applied to iterable objects.
Or objects which implement the iterator protocol ... meaning:
The object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator
Core objects which do that are:
Upvotes: 2