Member-only story
JavaScript Factory functions vs Constructor functions.

When it comes to the JavaScript Language comparing to other programming languages there are lots of words that you may hear or see really confusing to understand. One of them would be factory functions and the constructor functions.
Without further do let’s start with a definition for the factory functions.
Factory functions
A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so without the new
keyword, it’s a factory function.
function person(firstName, lastName, age) {
const person = {};
person.firstName = firstName;
person.lastName = lastName;
person.age = age; return person;
}
If you look at the above code inside the function, it creates a new object and attached passed arguments to that object as properties to that and return the new object. That is a simple factory function in JavaScript. Now let’s look at what is a Constructor function in JavaScript.
Constructor Functions
As opposed to the constructor functions they differ only from its use case and a convention. Other than that factory functions and constructor functions are similar. The convention of defining a constructor function is to use capitalize function name to denote that this is a constructor function, the use case of this function is that creating similar types of objects with the new
keyword, then later we can do instance checks using theinstanceof
keyword in JavaScript. That is where we can clearly see the difference between factory and constructor functions. Following code shows how to define a constructor function. Will dig into more details soon.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
Creating Objects with new Keyword
As I explained above convention is to make functions that are meant to be invoked with new
start with a capital letter. I know that you have a few questions on your mind related to what we discussed by now. Probably those will be;