blog

  • Home
  • blog
  • Quick Tip: What Are Factory Functions in JavaScript

Quick Tip: What Are Factory Functions in JavaScript

You can’t get far as a JavaScript programmer without learning about functions and objects, and when used together, they are the building blocks we need to get started with a powerful object paradigm called composition. Today we’ll look at some idiomatic patterns for using factory functions to compose functions, objects and promises.

When a function returns an object, we call it a factory function.

Let’s take a look at a simple example.

function createJelly() {
  return {
    type: 'jelly',
    colour: 'red'
    scoops: 3
  };
}

Each time we call this factory, it will return a new instance of the jelly object.

It’s important to note that we don’t have to prefix our factory names with create but it can make the intent of the function clearer to others. The same is true with the type property but often it can help us differentiate between the objects flowing through our programs.

Parameterized Factory Functions

Like all functions, we can define our factory with parameters which change the shape of the returned object.

function createIceCream(flavour='Vanilla') {
  return {
    type: 'icecream',
    scoops: 3,
    flavour
  }
}

In theory, you could use parameterized factories with hundreds of arguments to return very specific and deeply nested objects, but as we’ll see, that’s not at all in the spirit of composition.

Composable Factory Functions

Defining one factory in terms of another helps us break complex factories into smaller, reusable fragments.

For example, we can create a dessert factory which is defined in terms of the jelly and ice cream factories from before.

function createDessert() {
  return {
    type: 'dessert',
    bowl: [
      createJelly(),
      createIceCream()
    ]
  };
}

We can compose factories to build arbitrarily complex objects that don’t require us to mess around with new or this.

Objects that can be expressed in terms of has-a relationships, rather than is-a can be implemented with composition, instead of inheritance.

For example, with inheritance.

// A trifle *is a* dessert

function Trifle() {
  Dessert.apply(this, arguments);
}

Trifle.prototype = Dessert.prototype;

// or

class Trifle extends Dessert {
  constructor() {
    super();
  }
}

We can express the same idea with composition.

Continue reading %Quick Tip: What Are Factory Functions in JavaScript%

LEAVE A REPLY