What are JavaScript Factory Functions?

A factory function is a function that creates and returns an object. Unlike constructor functions, factory functions don't require the new keyword and don't use this to reference object properties.

Factory functions are a simple and flexible way to create objects in JavaScript. They can include properties, methods, and default values, making object creation more convenient and reusable.

Key Features

Factory functions offer several advantages:

  • No need for the new keyword
  • No this binding issues
  • Can contain private variables through closures
  • Return objects directly
  • Allow for easy object customization

Basic Syntax

function factoryFunction(parameters) {
    return {
        property1: value1,
        property2: value2,
        method: function() {
            // method logic
        }
    };
}

Example: Employee Factory Function

Here's a simple factory function that creates employee objects:

<!DOCTYPE html>
<html>
<head>
    <title>Factory Function Example</title>
</head>
<body>
    <h1>Employee Factory Function</h1>
    <script>
        // Factory function creating employee objects
        function createEmployee(name, department) {
            return {
                name: name,
                department: department,
                introduce: function() {
                    console.log('Hello, I am ' + this.name + ' from ' + this.department + ' department.');
                },
                work: function() {
                    console.log(this.name + ' is working...');
                }
            };
        }
        
        // Creating employees without 'new' keyword
        const emp1 = createEmployee('Steve Jobs', 'Innovation');
        const emp2 = createEmployee('Bill Gates', 'Technology');
        
        emp1.introduce();
        emp1.work();
        emp2.introduce();
        emp2.work();
    </script>
</body>
</html>
Hello, I am Steve Jobs from Innovation department.
Steve Jobs is working...
Hello, I am Bill Gates from Technology department.
Bill Gates is working...

Example: Student Factory with Multiple Properties

This example shows a more complex factory function with multiple parameters and methods:

<!DOCTYPE html>
<html>
<head>
    <title>Student Factory Function</title>
</head>
<body>
    <h1>Student Factory Function</h1>
    <script>
        // Factory function creating student objects
        function createStudent(rollNo, name, age, grade) {
            return {
                rollNo: rollNo,
                name: name,
                age: age,
                grade: grade || 'Not Assigned',
                getDetails: function() {
                    return 'Student: ' + this.name + 
                           ', Roll No: ' + this.rollNo + 
                           ', Age: ' + this.age + 
                           ', Grade: ' + this.grade;
                },
                study: function(subject) {
                    console.log(this.name + ' is studying ' + (subject || 'general subjects'));
                }
            };
        }
        
        // Creating student objects
        const student1 = createStudent(101, 'Alice', 16, 'A');
        const student2 = createStudent(102, 'Bob', 17);
        
        console.log(student1.getDetails());
        student1.study('Mathematics');
        
        console.log(student2.getDetails());
        student2.study('Science');
    </script>
</body>
</html>
Student: Alice, Roll No: 101, Age: 16, Grade: A
Alice is studying Mathematics
Student: Bob, Roll No: 102, Age: 17, Grade: Not Assigned
Bob is studying Science

Factory Functions vs Constructor Functions

Feature Factory Functions Constructor Functions
new keyword Not required Required
this binding No issues Can have binding issues
Return statement Explicit return Implicit return (when using new)
Flexibility High Moderate

Advantages of Factory Functions

Factory functions provide several benefits:

  • Simplicity: No need to remember new keyword
  • Flexibility: Can return different object types based on parameters
  • Encapsulation: Can create private variables using closures
  • No prototype confusion: Direct object creation

Conclusion

Factory functions offer a simple and flexible approach to object creation in JavaScript. They eliminate common pitfalls associated with constructor functions while providing clean, readable code for creating objects with shared properties and methods.

Updated on: 2026-03-15T23:19:00+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements