Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to spread a function. Are normal functions iterable in javascript

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?

like image 749
Abhishek Avatar asked Dec 24 '22 08:12

Abhishek


2 Answers

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);
like image 101
Suren Srapyan Avatar answered Dec 25 '22 20:12

Suren Srapyan


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
like image 32
Nina Scholz Avatar answered Dec 25 '22 20:12

Nina Scholz