Objects and Factory functions in JavaScript

“In JavaScript, objects are king. If you understand objects, you understand JavaScript.” -W3schools.com. If you’re learning JavaScript then you will eventually run into objects and hopefully, after reading this you’ll be ready for them.


Objects in JavaScript can be thought of like variables, they can hold data but instead of just holding one data value they can hold multiple different kinds. Objects are containers for named values called properties. The values are written as name: value pairs and separating each pair is a comma. Along with normal properties, an object can also have methods. Methods are a property with a function definition, they are actions that can be performed on the object it’s held in. Instead of being written as a `name: value` pair, the method will be the function name, parentheses for if you have parameters and curly brackets that will hold everything the function will do. The example below shows the object template, proper use of both properties, methods, and the invocation of the object method. Within the object method, you’ll see that I use the this keyword, for more information on that you can go here.

Now we have an object with its own properties and methods. Objects can be convenient, though if we need more than a few it can get a little tedious to keep making different objects that will have all the same values. This is where factory functions can come in and save the day.


Factory functions are functions that return objects. The objects that are returned are similar in the way that they have the same properties but they’ll be different because those properties have different set values.

With the factory function template above we can make multiple objects from just that one function. First, we’ll make a variable to hold the new object and initialize it to the invocation of the factory function. The parameters that we pass in will become the value in our name: value pairs. These new objects can be used just like the objects we made before, but now each object will be held in its own unique variable with its own unique values.

As you can see we’ve made objects that take the same format and implications as the ones from before but we’ve saved so many lines of code.

Factory functions will make your Object Orientated coding easier to read, easier to run, and just more coherent in general. Getting stuck on a topic like this super common but as long as you take your time and absorb all the information and not give up you’ll be fine.

Just a coder trying to help people code