JavaScript Factory Functions with ES6+

Eric Elliott
Jul 20, 2017 · 10 min read
Image for post
Image for post
Smoke Art Cubes to Smoke — MattysFlicks — (CC BY 2.0)
const user = {
userName: 'echo',
avatar: 'echo.png'
};
console.log(user.userName); // "echo"
const key = 'avatar';console.log( user[key] ); // "echo.png"
const userName = 'echo';
const avatar = 'echo.png';
const user = {
userName,
avatar
};
console.log(user);
// { "avatar": "echo.png", "userName": "echo" }
const userName = 'echo';
const avatar = 'echo.png';
const user = {
userName,
avatar,
setUserName (userName) {
this.userName = userName;
return this;
}
};
console.log(user.setUserName('Foo').userName); // "Foo"

Literals for One, Factories for Many

If you need to create many objects, you’ll want to combine the power of object literals and factory functions.

const createUser = ({ userName, avatar }) => ({
userName,
avatar,
setUserName (userName) {
this.userName = userName;
return this;
}
});
console.log(createUser({ userName: 'echo', avatar: 'echo.png' }));/*
{
"avatar": "echo.png",
"userName": "echo",
"setUserName": [Function setUserName]
}
*/

Returning Objects

Arrow functions (=>) have an implicit return feature: if the function body consists of a single expression, you can omit the return keyword: () => 'foo' is a function that takes no parameters, and returns the string, "foo".

const noop = () => { foo: 'bar' };
console.log(noop()); // undefined
const createFoo = () => ({ foo: 'bar' });
console.log(createFoo()); // { foo: "bar" }

Destructuring

Pay special attention to the function signature:

const createUser = ({ userName, avatar }) => ({
const swap = ([first, second]) => [second, first];console.log( swap([1, 2]) ); // [2, 1]
const rotate = ([first, ...rest]) => [...rest, first];console.log( rotate([1, 2, 3]) ); // [2, 3, 1]

Computed Property Keys

Earlier we used square bracket computed property access notation to dynamically determine which object property to access:

const key = 'avatar';console.log( user[key] ); // "echo.png"
const arrToObj = ([key, value]) => ({ [key]: value });console.log( arrToObj([ 'foo', 'bar' ]) ); // { "foo": "bar" }
{ [key]: value }
{ "foo": "bar" }

Default Parameters

Functions in JavaScript support default parameter values, which have several benefits:

  1. The function is more self-documenting because default values supply examples of expected input.
  2. IDEs and static analysis tools can use default values to infer the type expected for the parameter. For example, a default value of 1 implies that the parameter can take a member of the Number type.
const createUser = ({
userName = 'Anonymous',
avatar = 'anon.png'
} = {}) => ({
userName,
avatar
});
console.log(
// { userName: "echo", avatar: 'anon.png' }
createUser({ userName: 'echo' }),
// { userName: "Anonymous", avatar: 'anon.png' }
createUser()
);
} = {}) => ({

Type Inference

JavaScript does not have any native type annotations as of this writing, but several competing formats have sprung up over the years to fill the gaps, including JSDoc (in decline due to the emergence of better options), Facebook’s Flow, and Microsoft’s TypeScript. I use rtype for documentation — a notation I find much more readable than TypeScript for functional programming.

Image for post
Image for post
Without defaults, the type is unknown for `userName`.
Image for post
Image for post
With defaults, the IDE can suggest that `userName` is expecting a string.

Factory Functions for Mixin Composition

Factories are great at cranking out objects using a nice calling API. Usually, they’re all you need, but once in a while, you’ll find yourself building similar features into different types of objects, and you’ll want to abstract those features into functional mixins so you can reuse them more easily.

const withConstructor = constructor => o => ({
// create the delegate [[Prototype]]
__proto__: {
// add the constructor prop to the new [[Prototype]]
constructor
},
// mix all o's props into the new object
...o
});
import withConstructor from `./with-constructor';const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
// or `import pipe from 'lodash/fp/flow';`
// Set up some functional mixins
const withFlying = o => {
let isFlying = false;
return {
...o,
fly () {
isFlying = true;
return this;
},
land () {
isFlying = false;
return this;
},
isFlying: () => isFlying
}
};
const withBattery = ({ capacity }) => o => {
let percentCharged = 100;
return {
...o,
draw (percent) {
const remaining = percentCharged - percent;
percentCharged = remaining > 0 ? remaining : 0;
return this;
},
getCharge: () => percentCharged,
getCapacity: () => capacity
};
};
const createDrone = ({ capacity = '3000mAh' }) => pipe(
withFlying,
withBattery({ capacity }),
withConstructor(createDrone)
)({});
const myDrone = createDrone({ capacity: '5500mAh' });console.log(`
can fly: ${ myDrone.fly().isFlying() === true }
can land: ${ myDrone.land().isFlying() === false }
battery capacity: ${ myDrone.getCapacity() }
battery status: ${ myDrone.draw(50).getCharge() }%
battery drained: ${ myDrone.draw(75).getCharge() }% remaining
`);
console.log(`
constructor linked: ${ myDrone.constructor === createDrone }
`);

Conclusion

ES6 provides a convenient syntax for dealing with object creation and factory functions. Most of the time, that’s all you’ll need, but because this is JavaScript, there’s another approach that makes it feel more like Java: the class keyword.

Next Steps

Want to learn more about object composition with JavaScript?

Image for post
Image for post

JavaScript Scene

JavaScript, software leadership, software development, and…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store