I am doing something like the below code in console
function add(a,b){return a+b;};
const obj = {...add};
To my surprise it doesn't throw an error. And neither do
const obj = {...123};
Spread syntax should be applicable to only iterable entities like objects, arrays, string, map, set, etc. So why does it doesn't throw an error when using non-iterable entities? Or am I missing something here?
Functions in JavaScript are also objects
. It has it's own properties like name
, call
, apply
and others.
Doing const obj = {...add}
just gets the enumerable properties of the function object
, put them into another object and assigns to the obj
. You can check via
function add(a,b){return a+b;};
add.test = 1;
const obj = {...add};
console.log('test' in obj);
What about 123
it is converted to the Number
wrapper and the rest is the same
const obj = {...123};
console.log('valueOf' in obj);
What you have is a spread syntax ...
for object literals (which is not supported in all user agents).
Spread in object literals
The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.
function add(a, b) { return a + b; }
const obj = { ...add };
console.log(obj); // no properties because no own enumerable properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With