Factory & Constructor function in JS

Factory function

In factory functions, we don't use the new keyword to create an object.

Factory functions simply create an object and return it.

Factory functions can contain inner values, methods, etc. just like regular functions. They differ from regular functions as they always return an object.

Let's see an example.

function createRectangle(l,b) {

return rectangle = {

length: l,

breadth: b,

area: function() {

console.log(`area is ${l * b}`);

}

}

}

console.log(createRectangle(4, 2).area());

Output

area is 8

Factory functions come handy when 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 objects.

Constructor function

Constructor functions are used to define/ initialize objects. Unlike factory function, they don't return objects.

The this keyword is used to refer to inner values and the new keyword is used while instantaiting new objects.

function Rectangle(l,b) {

this.length = l;

this.breadth = b;

this.area = function() {

return this.length * this.breadth;

}

}

const rectangle = new Rectangle(4,5);

console.log(rectangle.area());

Output

20