🏭JavaScript: Factory Function 🏭

🏭JavaScript: Factory Function 🏭

Factory Function in JavaScript Explained with Examples.

Hey there!👋

In this tutorial, you will learn about the JavaScript factory functions which are functions that return objects.

A factory function is a normal function in JavaScript with one difference – It returns an object literal.

What is Factory Function in JavaScript🤔

The factory function is a plain JavaScript function that always creates and returns a new object. This is the only purpose of creating this function. It works like a constructor function or class, but the factory function does not use new or this keyword to create a JavaScript object.🤫

fac.png

When Should You Use JavaScript Factory Function?😶‍🌫️

Before using a factory function in your JavaScript code, you need to know the problems it solves or the requirements that it fulfills.💯

☝️Requirement 1:

If you need multiple objects with similar types of properties and methods with little difference.

For example

you want to create an object that describes a user. But you need similar types of objects for Sam, Chuks, Bob, etc.

const sam = {
    name: 'Sam',
    age: 21,
    greet() {
        return `Hello, my name is ${this.name}`;
    }
};

const chuks = {
    name: 'Chuks',
    age: 24,
    greet() {
        return `Hello, my name is ${this.name}`;
    }
};

This object has a name, age properties and a greet() method. If you create objects manually, you have to do this 3 times for 3 persons. Their properties and method are the same but property values are different.

The factory function can solve this issue. With this, you can create a blueprint of your object once and create as many objects as you want with that blueprint. In this way, you can create separate objects for each user with similar characteristics but with different values.

✌️ Requirement 2:

To reduce code duplication.😯

As you see, you don't have to write similar kinds of objects multiple times. Using the factory function, you will create a layout of your object one time then it will create objects for you.

It is saving your time and solves the problem of code duplication😉.

👌Requirement 3:

To organize your code.🤓

By adding all the logic in one place, a factory function helps us to organize our code. When you read your code after some time or anyone else read the source code he/she will understand what this function is doing.

So, without writing many many similar types of functions all over your code, you write once in one place and use it whenever it is required.

It's a much better approach when you want to arrange and manage your source code.😌

🖖Requirement 4:

When you want to create your objects in a simple way.

One of the main reasons developers sometimes prefer factory functions over constructor functions or classes is that it is simple.

A factory function is just a plain JavaScript function that returns an object. That's all you need to know when you try to use it. You don't have to use new keyword or this keyword with your factory function.

Sometimes the this keyword is hard to handle especially if you don't know how it behaves in different situations. You can also create objects using the constructor function or class. In that case, you have to work with the this keyword.

That's why factory functions are simple and easy to use for creating new objects.🤗

Deep dive with Example 💪

A factory function is a function that returns a new object. The following creates a user object named user1:

let user1 = {
  firstName: 'Sam',
  lastName: 'Menson',
  getFullName() {
    return this.firstName + ' ' + this.lastName;
  },
};

console.log(person1.getFullName());

Output:

Sam Menson

The user1 object has two properties: firstName and lastName, and one method getFullName() that returns the full name.

Suppose that you need to create another similar object called user2, you can duplicate the code as follows:

let user2 = {
  firstName: 'Chuks',
  lastName: 'Menson',
  getFullName() {
    return this.firstName + ' ' + this.lastName;
  },
};

console.log(user2.getFullName());

Output:

Chuks Menson

In this example, the user1 and user2 objects have the same properties and methods. The problem is that the more objects you want to create, the more duplicate code you have.🤯

To avoid copying the same code all over again, you can define a function that creates the user object:

function createUser(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName() {
      return firstName + ' ' + lastName;
    },
  };
}

When a function creates and returns a new object, it is called a factory function. The createUser() is a factory function because it returns a new person object.

The following 👇 show how to use the createUser() factory function to create two objects user1 and user2:

function createUser(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName() {
      return firstName + ' ' + lastName;
    },
  };
}

let user1 = createPerson('Sam', 'Menson');
let user2 = createPerson('Chuks', 'Menson');

console.log(user1.getFullName());
console.log(user2.getFullName());

By using the factory function, you create any number of the person objects without duplicating code.🤠

Conclusion 🙇‍♀️

In JavaScript, a Factory function is a type of function that returns an object and does not require the usage of a new keyword. It can be used for initializing an object, similar to a constructor. It is also considered a useful tool that permits you to produce multiple object instances quickly. This write-up discussed Factory functions in JavaScript.👩‍🦰

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!