Factory Function

A factory function is any function that is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so without the new keyword, it’s a factory function.

Factory functions have always been attractive in JavaScript because they offer the ability to easily produce object instances without diving into the complexities of classes and the new keyword. Prior to ES6, there was a lot of confusion about the differences between a factory function and a constructor function in JavaScript. Since ES6 has the class keyword, a lot of people seem to think that solved many problems with constructor functions. It didn’t. Let’s explore the major differences you still need to be aware of. Nice note: In JavaScript, any function can return a new object.

When it’s not a constructor function or class, it’s called a factory function.

let jane = {
    firstName: 'Jane',
    lastName: 'Doe',
    getFullName() {
        return this.firstName + ' ' + this.lastName;
    }
};

console.log(jane.getFullName());

Last updated