It’s pretty easy to make an object in JavaScript once you know the syntax, but if you want to make more than one of the same type of object, it’s better to do it from some kind of blueprint so that all those objects are structurally the same and you can run the same logic over them without it breaking. And in general it’ll make your code leaner.

A good real world object that you might do this with is a book in an online database for a library. So we can start with an object literal to kick things off:

let book = {
  title:                'The Left Hand of Darkness',
  author:               'Ursula K. Le Guin',
  firstPublished:       1969,  
  thisVersionPublished: 2016,
  publisher:            'Penguin Random House',
}

You can imagine this object might have more data, but we’ll leave it here for this example. In a library there are thousands of books, so we’ll probably need thousands of these book objects. We don’t want to keep retyping out objects and duplicating the keys of the objects because there is a big scope for error here.

Factory Functions

Rather than that, we can make a function that reproduces the book objects and spits them back out. There’s more than one way to do this, but a pretty simple one is to build a factory function. It spits out objects with a fixed structure just like a factory can. To change the book object to a factory function, we can just return the object from a function and set all the values of the key-value pairs using parameters to that function, like this:

function book(title,author,firstPublished,thisVersionPublished,publisher) {
  return {
    title:                title,
    author:               author,
    firstPublished:       firstPublished,  
    thisVersionPublished: thisVersionPublished,
    publisher:            publisher
  }
}

const book1 = book('The Left Hand of Darkness', 'Ursula K. Le Guin', 1969, 2016, 'Penguin Random House');

console.log(book1);

> {title: 'The Left Hand of Darkness', author: 'Ursula K. Le Guin', firstPublished: 1969, thisVersionPublished: 2016, publisher: 'Penguin Random House'}

Now, mistakes can still be made in the data that’s passed in, but it’s structurally sound and the same for every object that the book factory function produces. We can even make it cleaner using ES6 syntax:

function book(title,author,firstPublished,thisVersionPublished,publisher) {
  return {
    title,
    author,
    firstPublished,  
    thisVersionPublished,
    publisher,
  }
}

const book1 = book('The Left Hand of Darkness', 'Ursula K. Le Guin', 1969, 2016, 'Penguin Random House');

console.log(book1);

> {title: 'The Left Hand of Darkness', author: 'Ursula K. Le Guin', firstPublished: 1969, thisVersionPublished: 2016, publisher: 'Penguin Random House'}

In ES6, if the key and the value for that key are the same, then you can conflate them into a single value. As in the above example, the key ‘title’ and the parameter ‘title’ are the same so we can just use title in the first line of the return statement. (Also the case for author, firstPublished, thisVersionPublished etc). This is referred to as shorthand notion.

Now we can call this function as many times as we like to make as many books as we have.

Methods in Factory Functions

If we imagine that we’re building the back end of the online library, then a librarian might be sitting there entering information into the books list. When they click on the save button, the info they entered would be saved into a database. To do this, the book function needs a save method, something like:

function book(title,author,firstPublished,thisVersionPublished,publisher) {
  return {
    title,
    author,
    firstPublished,  
    thisVersionPublished,
    publisher,
    save(){
      // some api calls to get the book into the db
      console.log(`Saving the book ${title} into the database`);
    }
  }
}

const book1 = book('The Left Hand of Darkness', 'Ursula K. Le Guin', 1969, 2016, 'Penguin Random House');

book1.save();
> Saving the book The Left Hand of Darkness into the database...

NOTE, this save function is in ES6 syntax and contains a template literal – for older JS, it would look like this:

save: function(){
   // some api calls to get the book into the db
   console.log('Saving the book ' + title + ' into the database');
}

Now we have a function we can use to make multiple book objects in a controlled way, all with the same structure!

Afterthought

If you want to know a bit about the factory that is in the featured image of this post, it’s the old power station at White Bay, Rozelle in Sydney, taken from the carpark of the nearby Kennards Self Storage. It has been a feature of the landscape and my life in inner Sydney for a very long time and I think, a really beautiful one!

Factory Functions in JavaScript – making more than one object
Tagged on:         

Leave a Reply

Your email address will not be published.