Factory Functions in Javascript

Sara Cemal
2 min readApr 29, 2021

--

Using factory functions to speed up the creation of instances of an object

Before we get too deep into this concept, it’s an important reminder to remember that everything within Javascript is an object. Yes, everything. Within Javascript, objects are important in order to store data, and can be organized in key value pairs if they contain multiple properties.

For example:

Creating individual objects works, and we could create them each individually, just like the example above. However, thankfully we are coding, and there are almost always ways to make tasks easier (or we could code it ourselves 😎). With that being said, let’s say we need to create several instances of an object quickly. This is where factory functions come in.

Using a definition from Codecademy, a factory function is a function that returns an object and can be reused to make multiple object instances. You can utilize the parameters within the function to help customize the object that gets returned.

For example, let’s say that we are working on a project where we need to keep track of students. Using a factory function, you can create these student instances quicker, and not have to create an object literal each time a new student enrolls. You are able to invoke the factory function with the proper arguments to create new students much easier.

So, instead of using the code in the snippet above, we could do something similar to this:

And there you have it! You are able to interact with these objects just like you would other objects, but hopefully factory functions are something you can utilize to your advantage for quicker object creation.

--

--

Sara Cemal
Sara Cemal

Written by Sara Cemal

Flatiron School alumni with a sociology and neuroscience background.

No responses yet