Reputation: 1247
I just found {....0}
in friend's code. Evaluating it in console returns {}
(empty object).
Why is that? What is the meaning of 4 dots in JavaScript?
Upvotes: 79
Views: 9717
Reputation: 2483
Spread operator {...}
allows iterables to expand. It means that those data types that can be defined in form of key-value
pairs can be expanded. In terms of Object
we call key-value pair as Object property and it's value whereas in terms of arrays
we can think index as key and element in array as it's value.
let obj = { a: 4, b: 1};
let obj2 = { ...obj, c: 2, d: 4}; // {a: 4, b: 1, c: 2, d: 4}
let arr1 = ['1', '2'];
let obj3 = { ...arr1, ...['3']}; // {0: "3", 1: "2"}
In terms of array, as it takes index as key so here it replaces element '1' of arr1
with '3' because both of them have same index in different array.
With strings too spread operator returns non-empty object. As string is an array of character so it treats string as an array.
let obj4 = {...'hi',...'hello'} // {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}
let obj5 = {...'y',...'x'} // {0: "x" }
But with other primitive data types it return empty object
with Numbers
let obj6 = { ...0.0, ...55} // {}
with Boolean
let obj7 = { ...true, ...false} // {}
In conclusion those data types that can be treated in form of key-value pairs when used with spread operator {...}
returns non-empty object otherwise it returns empty object {}
Upvotes: 1
Reputation: 138537
Three dots in an object literal are a spread property, e.g.:
const a = { b: 1, c: 1 };
const d = { ...a, e: 1 }; // { b: 1, c: 1, e: 1 }
The last dot with a 0 is a number literal .0
is the same as 0.0
. Therefore this:
{ ...(0.0) }
spreads all properties of the number object into the object, however as numbers don't have any (own) properties you get back an empty object.
Upvotes: 56
Reputation: 2387
In a simple terms {...}
spread operator in javascript extends one object/array with another.
So, when babelifier tries extending one with another, it has to identify whether it is trying to extend an array or an object.
In the case of array
, it iterates over elements.
In the case of object
, it iterates over keys.
In this scenario, the babelyfier is trying to extract keys for number
by checking the Object's own property call
which is missing for number
so it returns empty Object.
Upvotes: 6
Reputation: 4185
Four dots actually have no meaning. ...
is the spread operator, and .0
is short for 0.0
.
Spreading 0 (or any number) into an object yields an empty object, therefore {}
.
Upvotes: 90