Open In App

What are factory functions in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors.

Why it is useful?

If we have complex logic, and we have to create multiple objects again and again that have the same logic, we can write the logic once in a function and use that function as a factory to create our objects. It’s the same as a real-world factory producing products.

Example 1: We have a factory function that will produce new robots with a single logic. Using this we can produce as many objects/robots as we want.

Javascript




// Function creating new objects
// without use of 'new' keyword
function createRobot(name) {
    return {
        name: name,
        talk: function () {
            console.log('My name is '
                + name + ', the robot.');
        }
    };
}
 
//Create a robot with name Chitti
const robo1 = createRobot('Chitti');
 
robo1.talk();
 
 
// Create a robot with name Chitti 2.O Upgraded
const robo2 = createRobot('Chitti 2.O Upgraded');
 
robo2.talk();


Output

My name is Chitti, the robot.
My name is Chitti 2.O Upgraded, the robot.

Example 2: In this example, the Person factory function efficiently creates person objects by encapsulating the process of setting name and age properties. Each person object includes a greeting method for generating a customized message. Instances, such as person1 and person2, are easily created using the factory function, showcasing a concise and reusable approach to object creation in JavaScript.

Javascript




// Factory Function creating person
let Person = function (name, age) {
 
    // creating person object
    let person = {};
 
    // parameters as keys to this object 
    person.name = name;
    person.age = age;
 
    // function to greet
    person.greeting = function () {
        return (
            'Hello I am ' + person.name
            + '. I am ' + person.age
            + ' years old. '
        );
    };
    return person;
};
 
let person1 = Person('Abhishek', 20);
console.log(person1.greeting());
 
let person2 = Person('Raj', 25);
console.log(person2.greeting());


Output

Hello I am Abhishek. I am 20 years old. 
Hello I am Raj. I am 25 years old. 



Last Updated : 09 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads