Factory Functions Vs Constructor Functions in JavaScript.

The ERIN
2 min readAug 19, 2020

--

I started the #100DaysOfCode challenge today, you can join me on this challenge here

I’ll be kicking this challenge off with a very interesting yet confusing topic on JavaScript, The Factory Functions And The Constructor Functions.

Factory Functions

Factory Functions are functions which are neither classes or constructors. If a function returns a new object without the new keyword,they are said to be a Factory Function. The Naming Convention used here is the Camel Notation. Let’s see an example of a Factory function

Example of Factory Function

In the Example above,a function called productDetails was created. Inside the function, an argument was passed to the object created as properties and return the new object.

In Factory Function all our Logic is defined in one place, so there is no need duplicate for creation of every object. This will reduce debugging headaches if we found any bug in our function some time in the future.

Constructor Functions

Constructor Functions are used to construct or create an object. It is another pattern for creating objects just like the Factory Functions. It differs from the Factory Function in its use case and naming convention. The naming convention used in Constructor Function is the Pascal Notation, in this notation the first letter of every word should be Uppercase. Let’s see an example of a Constructor Function

Example of Constructor Function

In the example above, the new keyword operator created an empty JavaScript object. Next we use the this keyword to point the properties of ‘this.name’ and ‘this.price’ to the empty object that was created by the new keyword. Finally, the new keyword operator will return the new object from the function.

Thank You For Reading this Article, you can keep up with my progress by following me on my social media accounts.

Twitter: twitter.com/jhimmyofficial

--

--