hally9k hally9k - 1 year ago 100
Javascript Question

es6 syntax for factory

Could someone please explain how the following es6 code is a factory.
I have stared at the syntax for a full minute and still don't understand how this explicitly returns a new instance of the chat object.

const createChat = ({
id = 0,
msg = '',
user = 'Anonymous',
timeStamp = 1472322852680
} = {}) => ({
id, msg, user, timeStamp

Answer Source

All the values you see (0, '', Anonymous, 1472322852680) are the default values. They would normally be extracted from the passed in object but if they don't exist these are what will be used in their place. This is default parameters.

The => ({...}) is shorthand to return the value (notice there is no return statement). So here it is returning an object with the passed in id, msg, user, and timeStamp unless those values aren't passed in. It is accomplishing this by using destructing.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download