What are Factory Functions and why are they better than object constructors?

What are Factory Functions and why are they better than object constructors?

What are Factory Functions?

Factory functions are a way of creating objects without dealing with classes or the new keyword.

Let's do a quick recap of how to create an object. There are 2 ways to create an object, using an object literal and constructors and instantiating it with the new keyword.

//Object literal
let object = {
    prop1: "first property",
    prop2: "second property"
}

//Object constructor
function object (prop1, prop2, prop3){
    this.prop1 = prop1,
    this.prop2 = prop2,
    this.prop3 = prop3
}

//Instance of Object constructor
let objectInstance = new object("first property", "second property", "third property");

With factory functions, instead of using the new keyword whenever creating an object, factory functions simply set and return that function every time it’s being called.

const BookFactoryFunction = (title, author, pages) =>{
  const info = console.log(`${title} by ${author} and has ${pages} number of pages`);

  return{ info }
}

That means instead of created objects individually, we can create multiple objects in bulk at the same time.

const theHobbit = BookFactoryFunction('The Hobbit', 'J.R. Tolkien', 295);
const deepWork = BookFactoryFunction('Dee Work', 'Cal Newport', 296);
const atomicHabits = BookFactoryFunction('Atomic Habits', 'James Clear', 295);

This makes it easy when it comes to dealing with issues related to inheritance.

Not just inheritance issues, when you create an object(the generic way), you give it properties, e.g. name, age, and so on. That can be a downside and create bugs that are hard to track, e.g. you change the name of the object and then you call a method of that object, the whole name changes, but with factory functions, you don’t even get to create those properties, talkless of creating those bugs.

Factory functions use something called composition which is better than inheritance in some cases. In the next article, I'll be talking about composition and why it's better than inheritance.