Factory functions Vs Constructor Functions


** Factory functions **

Factory functions are used to produce objects. Let's see an example of the factory function.


function productDetails(name, price, description){
 return {
   name,
   price,
   description,
   recommendedProducts(){
     console.log('products');
    }
  };
}
const product = productDetails('bread', '3$', 'Milk bread');

So the uses of factory function is our logic is defined in one place. So there is no need duplicate for creation of every object. In future if we found any bug in th function we can fix it in one place.

** Constructor functions **

Constructor functions are used to construct or create an object. Let's see an example of the Constructor function.

function ProductDetails(name, price, description){
 this.name = name;
 this.price = price;
 this.description = description;
 this.recommendedProducts = function(){
  console.log('products');
 }
}

const product = new ProductDetails('bread', '3$', 'Milk bread');


In the constructor function, the new keyword is used to call a function. By using the new keyword function will return an empty object product in the above case and point out this keyword to the product object. Whereas in factory functions, the object will be created with the function call.