Open In App
Related Articles

What are factory functions in JavaScript ?

Like Article
Save Article
Report issue

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.


// 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');;
// Create a robot with name Chitti 2.O Upgraded
const robo2 = createRobot('Chitti 2.O Upgraded');;


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.


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


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
Share your thoughts in the comments
Similar Reads