Skip to content
Related Articles

Related Articles

Improve Article

What are factory functions in JavaScript ?

  • Last Updated : 24 Jun, 2021

The Factory Function is similar to constructor functions/class functions, but instead of using new to create an object, factory functions simply creates an object and returns it.

Factory Functions are a very useful tool in JavaScript. Factory Functions in JavaScript are similar to constructor functions/class functions, but they do not require the use of the ‘this‘ keyword for inner values or the use of the ‘new‘ keyword when instantiating new objects. Factory Functions can contain inner values, methods, etc. just like normal regular functions. Factory Functions differ from regular functions as they always return an object, which will contain any value, method, etc.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 exactly 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.0 Upgraded, the robot.

Example 2:


    // Factory Function creating person
    var Person = function (name, age) {
        // creating person object
        var 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;
    var person1 = Person('Abhishek', 20);
    var person2 = Person('Raj', 25);


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

My Personal Notes arrow_drop_up
Recommended Articles
Page :