This content originally appeared on DEV Community and was authored by Christian Fields
A Simple Introduction:
So, maybe you’re new to Javascript, and don’t know what a factory function is. Or maybe you’re a pro and you need a bit of a refresher. Either way, today we’re going over that exactly: factory functions, an easy and convenient way to mass produce objects to your heart’s desire.
Getting Started…
Let’s start by going over what a factory function actually is, and why it’d be useful.
A factory function is what we call a function that’s designed to easily create multiple objects with similar data to your specifications that you’d otherwise have to repeat over, and over, and over… which gets tedious and messy fast. Sometimes, we find ourselves needing a lot of… basically the same objects, and we don’t want to just type out the same variable for each one we need; for example, if you were trying to store users for a website, entities in a game, or whatever else you might need. That’s where these handy functions come in. For this post, we’re going to use that first example as… well, our example. So let’s make an object:
const person1 = {
firstName: "Mary Jane",
lastName: "Watson",
age: 23,
career: "modeling",
hobbies: ["stalking Peter Parker", "partying"]
}
We now have a basis for what our objects need to look like. From here, we could, of course, do the same thing several times over, manually making each object we need for each potentially infinite user of our hypothetical database… or, we could do what programmers do best, and use our problem solving skills to automate the process for us.
But how can we do that? Well, to start, we’ll need a function that makes an empty object, and it’ll obviously have to return it:
function factory() {
const newObj = {};
return newObj;
}
(Alternatively, we could’ve simply had the function return an anonymous object: return {};
)
So how do we make use of this? Well, we need to be able to pass in data, to begin with. How else will we tell the function what we want our object to hold? Let’s add a few parameters based on what our person1
object looks like.
function factory(firstName, lastName, age, career, hobbies) {
const newObj = {};
return newObj;
}
Now we’re able to pass in the data we want our object to have. But obviously, that alone isn’t enough, so we’ll have to assign the data to our object. It’s as simple as giving the object a key-value pair of the same name ({ firstName: firstName }
, for example), or, since our key is evaluating to its own value, we can just put its name in.
function factory(firstName, lastName, age, career, hobbies) {
const newObj = {
firstName,
lastName,
age,
career,
hobbies
};
return newObj;
}
Finished, but let’s do a little extra.
And just like that, we’re already done! We can call the function, pass in our values, and assign the result to a variable. Nice and easy. But we can do a little bit more with this that you might find useful as well: we can throw a function into our object, and every object we make with our factory function will have that function… (I’m saying “function” a lot, I know, but that’s kinda what this whole article is about.)
Let’s do something simple for this tutorial, but you could make this into literally anything. We’ll return the full name of the user, followed by their age.
function factory(firstName, lastName, age, career, hobbies) {
const newObj = {
firstName,
lastName,
age,
career,
hobbies,
full: function() {
return `${firstName} ${lastName}, ${age}`;
}
};
return newObj;
}
I used something called a “template literal” for mine, essentially a string in which you can evaluate expressions – something fun to look into on your own time – but you could do this with simply concatenation (adding strings together) like this: firstName + " " + lastName + ", " + age
.
And now we’re all done! Let’s make another user using our new factory function to show it off!
And the results of our (pretty minimal, considering the payoff) efforts!
const person2 = factory("Peter", "Parker", 23, "photographer", ["rescuing civilians", "preaching the importance of the responsibility that comes with power", "taking selfies"]);
// person2 now equates to the following object (excluding the function it has built in):
{
firstName: "Peter",
lastName: "Parker",
age: 23,
career: "photographer",
hobbies: ["rescuing civilians", "preaching the importance of the responsibility that comes with power", "taking selfies"]
}
And we can use this to mass produce objects of the same structure! I could set up, for example, a user input field which takes these values, and turn the results we get from submitting the form into one of these objects to store in our hypothetical-website-database. And as for the function, it works great!
console.log(person2.full()); // logs "Peter Parker, 23"!
And that’s all you really need to know! Customize your function to your heart’s content, modify info as you receive it if you want, give the object its own functions, and take pride in making effective use of the Don’t Repeat Yourself technique!
Just… try not to make too many spider-men…
This content originally appeared on DEV Community and was authored by Christian Fields