How would you know when to use factory functions?


#1

Question

How would you know when to use factory functions?

Answer

Since Factory Functions are meant to create alike objects in a way that makes it easier to produce in mass quantities, a possible example when you would think on using a factory function instead of making a regular object literal would be a social network where let’s say each profile is an object, if we wanted a very minimalistic user with only name, image, friends and posts we could dynamically create them with a factory function where we could also have methods to add friends and create posts:

const makeUser = (id, name, image) => {
  return({
    id,
    name,
    image,
    friends: [],
    posts: [],
    addFriend (friend) {
       this.friends.push(friend);
    },
    createPost (post) {
      this.posts.push(post);
    }
  })
}

Now every time a user wants to sign up in our very simple social network app when they click sign up, this function will be triggered and they will become a new user object, where if they decide to add a friend the .addFriend() method will trigger with the friend to be added to the friends array.